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 :)
The disabled attribute is a boolean attribute. When present, it specifies that an option should be disabled. A disabled option is unusable and un-clickable. The disabled attribute can be set to keep a user from selecting the option until some other condition has been met (like selecting a checkbox, etc.).
Simply append disabled="disabled" in the tag.
The disabled attribute is a boolean attribute. When present, it specifies that the element should be disabled. A disabled element is unusable. The disabled attribute can be set to keep a user from using the element until some other condition has been met (like selecting a checkbox, etc.).
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)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With