I want to disable or enable a textbox based on boolean value, I created this extension method:
public static IHtmlString MyTextBoxFor<TModel,TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel,TProperty>> expression,
object htmlAttributes,
bool disabled
)
{
var attributes = new RouteValueDictionary(htmlAttributes);
if (disabled)
{
attributes.Add("disabled", "\"disabled\"");
}
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
And that how I used:
<div class="col-md-10">
@Html.MyTextBoxFor(model => model.Body, new { @class = "form-control"}, true)
</div>
but its not working, I'm new to Htmlhelper class, though it's not hard to understand, but I certainly missed something!
Edit:
I tried this simple method, to find out the problem:
public static IHtmlString MyTextBox(this HtmlHelper htmlHelper,object htmlAttributes, bool disabled)
{
IDictionary<string, object> attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
//var attrs = new Dictionary<string,string>();
if (disabled)
{
attrs.Add("disabled", "disabled");
attrs.Add("value", "txxxxxxt");
}
return htmlHelper.TextBox("txtbx", attrs);
}
And that has been rendered:
<input id="txtbx" name="txtbx" type="text" value="System.Collections.Generic.Dictionary``2[System.String,System.String]">
TextBoxForwithhtmlAttributesas a parameter instead ofattributes?trueorfalseIDictionary<string, object> attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);disabledparameter, when you can pass it inhtmlattributeas{ disabled= (1==0)}.