How to bind data to Model's "Display" property with MVC3?

718 views Asked by At

I have a model:

public class TestModel {
  [Display(Name = "Date")]
  public DateTime Date { get; set; }
}

with Html.LabelFor helper method in Test.cshtml page

@Html.LabelFor(m => m.Date )

and use this page with 2 MVC action methods: Create and Update. Example:

public virtual ViewResult Create() {
 return View("Test");
}

public virtual ViewResult Update() {
 return View("Test");
}

and I want to display @Html.LabelFor(m => m.Date ) with Create page: "Date" and Update page: "Update Date" . I know if the normal way of MVC3 can't do this. I hope your ideal can edit Html.LabelFor hepler method or anything way to bind data to Html.LabelFor in action methods on the controller

2

There are 2 answers

1
ePezhman On BEST ANSWER

you can override editorfor like this How can I override the @Html.LabelFor template? but I think you can do it more easily with ViewBag:

public virtual ViewResult Create() {
 ViewBag.Title = "Create";
 return View("Test");
}

public virtual ViewResult Update() {
 ViewBag.Title = "Update";
 return View("Test");
} 

in view:

@string.format("{0} Date" , ViewBag.Title )
0
Sh7ne On

Adding a hiddenFor field will bind the data to your Model.

@Html.HiddenFor(m=>m.Date);

For override, please just look this answer

https://stackoverflow.com/a/5196392/5557777