MVC 4razor数据注释ReadOnly

ReadOnly属性似乎不在MVC 4中。可编辑(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

这样的事可能吗? https://stackoverflow.com/a/11702643/1339704

注意:

[可编辑(假)]无效

您可以创建这样的自定义帮助程序,以检查属性是否存在ReadOnly属性:

 public static MvcHtmlString MyTextBoxFor( this HtmlHelper helper, Expression> expression) { var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); // in .NET 4.5 you can use the new GetCustomAttribute() 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(); // 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; } } 

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

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

其呈现为:

   

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

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

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

实际上 – 看看这个答案

  public static MvcHtmlString MyTextBoxFor( this HtmlHelper helper, Expression> expression) { return helper.TextBoxFor(expression, new { @readonly="readonly" }) }