Set disable attribute based on a condition for Html.TextBoxFor

后端 未结 12 1199
清酒与你
清酒与你 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:41

    Actually, the internal behavior is translating the anonymous object to a dictionary. So what I do in these scenarios is go for a dictionary:

    @{
      var htmlAttributes = new Dictionary
      {
        { "class" , "form-control"},
        { "placeholder", "Why?" }        
      };
      if (Model.IsDisabled)
      {
        htmlAttributes.Add("disabled", "disabled");
      }
    }
    @Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })
    

    Or, as Stephen commented here:

    @Html.EditorFor(m => m.Description,
        Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })
    

提交回复
热议问题