I am outputting a textbox to the page using the Html helpers. I want to add the disabled attribute dynamically based on whether or not a boolean value in my model is true or false.
My model has a method that returns a boolean value:
<% =Model.IsMyTextboxEnabled() %>
I currently render the textbox like follows, but I want to now enabled or disable it:
<% =Html.TextBox("MyTextbox", Model.MyValuenew { id = "MyTextbox", @class = "MyClass" })%>
If the return value of Model.IsMyTextboxEnabled() == true I want the following to be output:
<input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" />
If it == false, I want it to output as:
<input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" disabled />
What is the cleanest way to do this?
This here should do the trick:
<%= Html.TextBox("MyTextbox", Model.MyValuenew,
(Model.IsMyTextboxEnabled() ? (object) new {id = "MyTextbox", @class = "MyClass"}
: (object) new {id = "MyTextbox", @class = "MyClass", disabled="true" })) %>
In your helper would you have a check in the code, when you are generating the html, that simply checks the bool and then either adds the disabled attribute or leaves it out?
This is a simply example and not well structrued but...
if (disabled)
return string.Format(CultureInfo.InvariantCulture, "<input type=text disabled/>", new object[] { HttpUtility.HtmlAttributeEncode(s), myTextBox });
Is this what you were asking?
EDIT:
Wait, I see now. I think you'll need to either create your own helper or extend the MVC textbox helper so that you can do it.
Either that or you can I think do something like;
<%= Html.TextBox("mytextbox","", new { disabled="true" } %>
The above is untested but something like that should work.
EDIT 2:
<% if (condition) {%>
<%= Html.TextBox("mytextbox", "", new {@readonly="readonly"}) %>
<%} else {%>
<%= Html.TextBox("mytextbox", "") %>
<%}
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