– How to assign a dynamic value to the label helper in MVC

I am working on a MVC 2.0 web application. In my form , i have non editable fields , so i wanted to display them as labels rather than textboxes.

I am strongly binding my model with view. So, i need to associate this label with one of the fields in model.

This is what i am trying to do:



But, it is displaying nothing..Please help


What basically i am trying to do is a add operation. i have a create view and that view has a form.

I am strongly binding this view with model.So , that i can directly associate form fields with the model Properties.


<label> Name</label> <%=Html.TextBoxFor(m=>

So, what ever i type into the textbox , it will be stored in in the model.

If the text entered is "Avinash" , then gives value "Avinash"

I think i am correct upto this extent:


I have a field which is readonly , the user can not change the value of it.

<label>Changed On</label>  <label> DateTime.Now </label>

How to bind m.ChangedOn with the labels values(DateTme.Now)

so that it will result in m.Changedon as


This is what i am writing..

                    <td >
                        <%=Html.LabelFor(Model=>Model.CreatedOn) %>:
                        <%=Html.HiddenFor(Model=>Model.CreatedOn) %>

Best Solution

You no need to wrap with <label>, since MVC LabelFor will automatically create those html tags for you

So change this



  <%= Html.LabelFor(model=>model.changedby) %>


If you want to send the data to the server while you post your form, make sure you have a data in a form fields. Only form fields like input,select,textarea are posted to server and not display tag value like label, span, div, etc

Still if you need to post the label value, you can use hidden with it

<%= Html.LabelFor(model=>model.changedby) %>
<%= Html.HiddenFor(model=>model.changedby) %>

If you have both, your hidden field will posted to server, which contains the same value

Controller code

public ActionResult Index()
MyviewModel model=new MyviewModel();
return View(model);

For Save

public ActionResult Save(MyviewModel model)

 model.ChangedOn; // this property will show you hidden value
 //If you need current time, since the rendered time was old. Its good to assign like below