MVC 4 razor Data Annotations ReadOnly

孤街浪徒 提交于 2019-12-05 03:57:51

You can create a custom helper like this that will check the property for the presence of a ReadOnly attribute:

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);
}

The attribute is simply:

public class ReadOnly : Attribute
{

}

For an example model:

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

I have verified this works with the follow razor code:

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

Which renders as:

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

If you need disabled instead of readonly you can easily change the helper accordingly.

KerSplosh

You could create your own Html Helper Method

See here: Creating Customer Html Helpers

Actually - check out this answer

 public static MvcHtmlString MyTextBoxFor<TModel, TProperty>(
         this HtmlHelper<TModel> helper, 
         Expression<Func<TModel, TProperty>> expression)
    {
        return helper.TextBoxFor(expression, new {  @readonly="readonly" }) 
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!