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
注:
[可编辑(false)]不起作用
您可以创建这样一个自定义帮助程序,检查属性是否存在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
,则可以轻松地相应地更改辅助对象。
您可以创建自己的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" })
}