Set optional disabled attribute

I want to disable all the fields in my form that matter when the page loads. For example, in this

<td>@Html.TextBoxFor(m => m.PracticeName, new { style = "width:100%", disabled = Model.PracticeName == String.Empty ? "Something Here" : "disabled" })</td> 

I want to write inline something like this. I do not want to use if-else and make my code larger. Using javascript / jquery is also not welcome.

I tried to write false / true, but 1. Perhaps this is not a cross browser. 2.Mvc analyzed it for strings like "True" and "False". So how can I do this?

PS I am using ASP.NET MVC 3 :)

+4
source share
2 answers

Seems like a good candidate for a special assistant:

 public static class HtmlExtensions { public static IHtmlString TextBoxFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex, object htmlAttributes, bool disabled ) { var attributes = new RouteValueDictionary(htmlAttributes); if (disabled) { attributes["disabled"] = "disabled"; } return htmlHelper.TextBoxFor(ex, attributes); } } 

which can be used as follows:

 @Html.TextBoxFor( m => m.PracticeName, new { style = "width:100%" }, Model.PracticeName != String.Empty ) 

The helper, obviously, can be done even further, so you do not need to pass an additional logical value, but it automatically determines whether the value of the default(TProperty) expression default(TProperty) , and it uses the disabled attribute.

Another possibility is an extension method as follows:

 public static class AttributesExtensions { public static RouteValueDictionary DisabledIf( this object htmlAttributes, bool disabled ) { var attributes = new RouteValueDictionary(htmlAttributes); if (disabled) { attributes["disabled"] = "disabled"; } return attributes; } } 

which you would use with the standard TextBoxFor :

 @Html.TextBoxFor( m => m.PracticeName, new { style = "width:100%" }.DisabledIf(Model.PracticeName != string.Empty) ) 
+5
source

I used Darin. However, when it came to data_my_custom_attribute , they did not appear as data-my-custom-attribute . So I changed Darin's code to handle this.

 public static RouteValueDictionary DisabledIf( this object htmlAttributes, bool disabled ) { RouteValueDictionary htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); if (disabled) { htmlAttributesDictionary["disabled"] = "disabled"; } return new RouteValueDictionary(htmlAttributesDictionary); } 
0
source

Source: https://habr.com/ru/post/1385340/


All Articles