Set disable attribute based on a condition for Html.TextBoxFor

后端 未结 12 1196
清酒与你
清酒与你 2020-11-28 06:13

I want to set disable attribute based on a condition for Html.TextBoxFor in asp.net MVC like below

@Html.TextBoxFor(model => model.ExpireDate, new { style         


        
12条回答
  •  心在旅途
    2020-11-28 06:40

    Is solved this using RouteValueDictionary (works fine as htmlAttributes as it's based on IDictionary) and an extension method:

    public static RouteValueDictionary AddIf(this RouteValueDictionary dict, bool condition, string name, object value)
    {
        if (condition) dict.Add(name, value);
        return dict;
    }
    

    Usage:

    @Html.TextBoxFor(m => m.GovId, new RouteValueDictionary(new { @class = "form-control" })
    .AddIf(Model.IsEntityFieldsLocked, "disabled", "disabled"))
    

    Credit goes to https://stackoverflow.com/a/3481969/40939

提交回复
热议问题