MVC 4剃须刀数据注释ReadOnly

Soe*_*hay 8 c# data-annotations razor jquery-mobile asp.net-mvc-4

ReadOnly属性似乎不在MVC 4中.可编辑(false)属性不能按照我希望的方式工作.

有类似的东西有效吗?

如果没有,那么我如何创建自己的ReadOnly属性,如下所示:

public class aModel
{
   [ReadOnly(true)] or just [ReadOnly]
   string aProperty {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

所以我可以这样说:

@Html.TextBoxFor(x=> x.aProperty)
Run Code Online (Sandbox Code Playgroud)

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

@Html.TextBoxFor(x=> x.aProperty , new { @readonly="readonly"})
Run Code Online (Sandbox Code Playgroud)

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

@Html.TextBoxFor(x=> x.aProperty , new { disabled="disabled"})
Run Code Online (Sandbox Code Playgroud)

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

这样的事可能吗? /sf/answers/819185041/

注意:

[可编辑(假)]无效

asy*_*ult 9

您可以创建这样的自定义帮助程序,以检查属性是否存在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);
}
Run Code Online (Sandbox Code Playgroud)

该属性简单地说:

public class ReadOnly : Attribute
{

}
Run Code Online (Sandbox Code Playgroud)

对于示例模型:

public class TestModel
{
    [ReadOnly]
    public string PropX { get; set; }
    public string PropY { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我已经使用以下剃刀代码验证了这项工作:

@Html.MyTextBoxFor(m => m.PropX)
@Html.MyTextBoxFor(m => m.PropY)
Run Code Online (Sandbox Code Playgroud)

其呈现为:

<input id="PropX" name="PropX" readonly="readonly" type="text" value="Propx" />
<input id="PropY" name="PropY" type="text" value="PropY" />
Run Code Online (Sandbox Code Playgroud)

如果您需要disabled而不是readonly您可以相应地轻松更改帮助程序.


Ker*_*osh 5

您可以创建自己的Html Helper方法

请参阅此处: 创建客户Html帮助程序

实际上 - 看看这个答案

 public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(
         this HtmlHelper<TModel> helper, 
         Expression<Func<TModel, TProperty>> expression)
    {
        return helper.TextBoxFor(expression, new {  @readonly="readonly" }) 
    }
Run Code Online (Sandbox Code Playgroud)