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
注意:
[可编辑(假)]无效
答案 0 :(得分: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);
}
该属性简单:
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
,则可以相应地轻松更改帮助。
答案 1 :(得分:5)
您可以创建自己的Html Helper方法
见这里: Creating Customer Html Helpers
实际上 - 请查看this answer
public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
return helper.TextBoxFor(expression, new { @readonly="readonly" })
}