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"})%>
To make this answer more complete have an @if(SetDisable) {}else{} and in the first set put the disable code, in the else, have an enabled textbox.
Just SET the TextBox Property Enabled = True / False for Enable / Disable Textbox Control. For ReadOnly SET TextBox Property ReadOnly = True / False for ReadOnly on/off Textbox. – In above ASP.Net Tutorials, we have learn How to enable Textbox control, Disable TextBox control and Readonly Textbox control in ASP.Net C#.
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.
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.
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