Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Disable Html Helper control using boolean value from Model

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?

like image 561
The Matt Avatar asked Aug 19 '09 23:08

The Matt


2 Answers

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" })) %>
like image 112
Simon Fox Avatar answered Nov 03 '22 09:11

Simon Fox


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", "") %>
<%}
like image 28
griegs Avatar answered Nov 03 '22 07:11

griegs