开发者

mvc 3 html attributes

开发者 https://www.devze.com 2023-02-16 00:37 出处:网络
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 furth

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 开发者_如何学JAVAhave 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


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


This is expected behaviour, only values form elements are added to your Model on POST so your label will be ignored. To get around this duplicate your label value in a hidden field

Html.HiddenFor(model => model.FieldName)

or

Html.Hidden("FieldName", model.FieldName) 
0

精彩评论

暂无评论...
验证码 换一张
取 消