Search code examples
asp.net-mvc-3razorasp.net-mvc-helperslabel-for

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


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


Solution

  • 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 )