I'm trying to dynamically set the disabled
attribute for the TextBoxFor
HtmlHelper
@Html.TextBoxFor(model => model.Street,
new
{
@class = "",
disabled = (Model.StageID==(int)MyEnum.Sth) ? "disabled" : ""
})
but even if there is disabled=""
it is the same as disabled="disabled"
. How to get around of this ?
You can make the input 'read only' by using 'readonly'. This will let the data be POSTED back, but the user cannot edit the information in the traditional fashion.
TextBoxFor() The TextBoxFor<TModel, TProperty>() is the generic extension method that creates <input type="text"> control. The first type parameter is for the model class, and second type parameter is for the property.
IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view. You can do the same things with both, but you should use typed views and TextboxFor when possible.
Just add the id property to the html-attributes. That will override the default id generated by the editorfor-helper-methode. Save this answer.
I have the same problem about month ago and I finished by using this extension method for it
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;
}
}
And after that you can use it like this
@Html.TextBoxFor(
model => model.Street,
new { @class = "" }.DisabledIf(Model.StageID==(int)MyEnum.Sth)
)
EDIT (after Paul's comment):
The using of data-xxx
html attributes may be mined by using the constructor of the System.Web.Routing.RouteValueDictionary class, since underscores will not be automatically converted to minus sign.
Use the method System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes instead: will solve this issue.
UPDATED CODE (Extension method body only)
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (disabled)
{
attributes["disabled"] = "disabled";
}
return attributes;
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