tags:

views:

671

answers:

2

Hi I have a Html.TextBox() and I need to make it disabled in certain conditions. With the TextArea it goes like this:

<%=primaryLang ? Html.TextArea("e.location", new { rows = 2, cols = 60 }) : Html.TextArea("e.location", new { rows = 2, cols = 60, disabled = "true" })%>

But with TextBox it is not possible:

    <%=primaryLang ? 
      Html.TextBox("e.startDate") : 
        Html.TextBox("e.startDate", new { disabled = "true"})%>

It will issue {disabled=true} in the value. This is because the only function which will allow you to pass the HtmlAttributes will require also the model to be passed. This view is strongly typed, and the model is automatically filled in.

If I pass it like this:

Html.TextBox("e.startDate", Model.e.startDate, new { disabled = "true"})

or like this:

Html.TextBox("e.startDate", null, new { disabled = "true"})

the GET version will work, but the POST version will issue a NullReferenceException. Both the above seem to have the exact same effect. Both will present the correct data from the model on GET.

If I leave it lust like this:

Html.TextBox("e.startDate")

it will work correctly, for both POST and GET...

Why? Any ways to accomplish?

Thanks! :)


Thanks to the answers below, I solved it like this:

<%=primaryLang ? 
        Html.TextBox("e.startDate") : 
          Html.Hidden("e.startDate") + Html.TextBox("e.startDate", null, new { disabled = "true"})%>
A: 

On the POST, the "Model" or "e" property is probably null.

You could try this:

<%if (Model != null && Model.e != null) { %>
<%=Html.TextBox("e.StartDate", Model.e.StartDate, primaryLang ? null :  new { disabled = "disabled" })%>
<%}%>
Jan Willem B
+3  A: 

Disabled HTML elements do not post back to the server. This is why you get a NullReferenceException when you manage to disable your element.

I'm not sure what you're trying to achieve but if you are not allowing e.startDate to be editable then you shouldn't need it to be posted back as you should already know the value. So you have two options.

  1. Display e.startDate as you were, but just set the value e.startDate in your post method to the default or ignore it completely.
  2. If you need the value posted back then display e.startDate as a label, then add a hidden field containing e.startDate for your posted back value.

Warning: Just because the element is disabled it doesn't mean that someone can't edit the value and post it back. It's just a recommendation. It's up to the browser how to display the field. If your POST code does accept the e.startDate value then anyone with access can edit that field using development tools.

David G
That's it, great! I solved it and edited the question with my workaround (pasting it here loses all indentation and is unreadable).
Palantir