Updated on Kisan Patel
Here, I will show you how to add conditional attribute to Razor HTML helpers in ASP.NET MVC Razor syntax?
For example, if you want to add @readonly = “readonly” attribute for some condition then you need to follow below approach:
@Html.EditorFor(model => model.Records, new { htmlAttributes = ViewData.Model.Type == 1 ? (object)new { @class = "form-control input-sm", @readonly = "readonly" } : (object)new { @class = "form-control input-sm" } })
In above code, i have used ternary operator for checking condition and adding attribute. If you want to use HTML.TextBox then you need to follow below approach:
@Html.TextBoxFor(model => model.Records, ViewData.Model.Type == 1 ? (object)new { @class = "form-control input-sm", @readonly = "readonly" } : (object)new { @class = "form-control input-sm" })