Mvc 3 html attributes

asp.net-mvc-3

i have been playing around with MVC. I am currently stumped on with html helper methods. One thing i have noticed is that I cant really cant apply the ASP.NET Web Form logic into MVC. To explain further, in ASP.NET I could create a Label control and assign it some text data and then read the text data.

However, in MVC, I cant seem to do the same with @Html.LabelFor/@Html.Label, I have realised that once you do a POST from your form, the value from the Label is not bound back into my view model. However, if I use an EditorFor or TextBoxFor, I can get values bound to my viewmodel upon POST.

My question what html hlper method should I use to display text as readonly but yet be able to bind back to my viewmodel upon post ? I have tried TextBoxFor with its html attributes set to disabled and readonly but no luck.

Appreciate any pointers.
thanks

Best Answer

You should be able to bind the readonly attribute to the TextBox by passing in htmlAttributes as the 2nd parameter of the TextBoxFor method:

<%=Html.TextBoxFor(m => m.SomeProperty, new { @readonly = "readonly" }) %>

On MSDN: InputExtensions.TextBoxFor Method (HtmlHelper, Expression>, Object)


If you're trying to maintain the Label value you can use a combination of the LabelFor and HiddenFor methods.

I don't know why you would need to do this though, since you should be able to get the DisplayText attribute or the Property Name from the property.

<%=Html.LabelFor(m => m.SomeProperty) %>
<%=Html.HiddenFor(m => m.SomeProperty) %>

but this doesn't make a lot of sense since the usual syntax would be:

<%=Html.LabelFor(m => m.SomeProperty) %>
<%=Html.TextBoxFor(m => m.SomeProperty) %>

Note that if you use the disabled attribute the input will not be posted when the form is submitted