Reputation: 15190
I want to disable all fields in my form, which have values when page is loaded. 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 don't want to use if-else and make my code larger. Using javascript/jquery doesn't welcome too.
I tried to write false/true, but 1.It maybe isn't cross-browser 2.Mvc parsed it to string like "True" and "False". So how can I do it?
P.S. I use ASP.NET MVC 3 :)
Upvotes: 5
Views: 1240
Reputation: 24719
I used Darin's answer. However, when it came to data_my_custom_attribute
, they were not rendered 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);
}
Upvotes: 0
Reputation: 1038710
Seems like a good candidate for a custom helper:
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 could be used like this:
@Html.TextBoxFor(
m => m.PracticeName,
new { style = "width:100%" },
Model.PracticeName != String.Empty
)
The helper could obviously be taken a step further so that you don't need to pass an additional boolean value but it automatically determines whether the value of the expression is equal to default(TProperty)
and it applies the disabled
attribute.
Another possibility is an extension method like this:
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
helper:
@Html.TextBoxFor(
m => m.PracticeName,
new { style = "width:100%" }.DisabledIf(Model.PracticeName != string.Empty)
)
Upvotes: 6