MVC 4 razor 数据注释只读

2023-12-19

ReadOnly 属性似乎不在 MVC 4 中。Editable(false) 属性不能按我希望的方式工作。

有类似的东西有效吗?

如果不是,那么我如何制作自己的 ReadOnly 属性,其工作方式如下:

public class aModel
{
   [ReadOnly(true)] or just [ReadOnly]
   string aProperty {get; set;}
}

所以我可以这样说:

@Html.TextBoxFor(x=> x.aProperty)

而不是这个(它确实有效):

@Html.TextBoxFor(x=> x.aProperty , new { @readonly="readonly"})

或这个(它确实有效,但未提交值):

@Html.TextBoxFor(x=> x.aProperty , new { disabled="disabled"})

http://view.jquerymobile.com/1.3.2/dist/demos/widgets/forms/form-disabled.html http://view.jquerymobile.com/1.3.2/dist/demos/widgets/forms/form-disabled.html

也许是这样的?https://stackoverflow.com/a/11702643/1339704 https://stackoverflow.com/a/11702643/1339704

Note:

[可编辑(假)] 不起作用


您可以创建一个像这样的自定义助手,它将检查属性是否存在ReadOnly属性:

public static MvcHtmlString MyTextBoxFor<TModel, TValue>(
    this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
    var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    // in .NET 4.5 you can use the new GetCustomAttribute<T>() method to check
    // for a single instance of the attribute, so this could be slightly
    // simplified to:
    // var attr = metaData.ContainerType.GetProperty(metaData.PropertyName)
    //                    .GetCustomAttribute<ReadOnly>();
    // if (attr != null)
    bool isReadOnly = metaData.ContainerType.GetProperty(metaData.PropertyName)
                              .GetCustomAttributes(typeof(ReadOnly), false)
                              .Any();

    if (isReadOnly)
        return helper.TextBoxFor(expression, new { @readonly = "readonly" });
    else
        return helper.TextBoxFor(expression);
}

属性很简单:

public class ReadOnly : Attribute
{

}

对于示例模型:

public class TestModel
{
    [ReadOnly]
    public string PropX { get; set; }
    public string PropY { get; set; }
}

我已经使用以下剃刀代码验证了这一点:

@Html.MyTextBoxFor(m => m.PropX)
@Html.MyTextBoxFor(m => m.PropY)

其呈现为:

<input id="PropX" name="PropX" readonly="readonly" type="text" value="Propx" />
<input id="PropY" name="PropY" type="text" value="PropY" />

如果你需要disabled代替readonly您可以轻松地相应地更改助手。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC 4 razor 数据注释只读 的相关文章

随机推荐