UrbanPlanet
UrbanPlanet

Reputation: 105

DisplayName Attribute for complex datatypes in ASP.NET Razor MVC

I have a very simple requirement. In MVC4 project I have to show a form with @HTML.labelFor field derives values from attribute fields of a properties of viewmodel class. It works fine for simple properties such as Employee Code how ever it does not work for custom datatypes of person class.

namespace MvcApplication1.Models
{
  public class EmployeeViewModel
  {
    [Display(Name = "Employee Code:")]
    public string EmpCode { get; set; }

    public person PersonInfo { get; set; }

    [Display(Name = "Department Name:")]    
    public string Department { get; set; }
  }
}

namespace MvcApplication1.Models
{
  public class Person
  {
    [Display(Name = "First Name:")]
    public string FName { get; set; }

    [Display(Name = "Last Name:")]
    public string LName { get; set; }
  }
}

@Html.LabelFor(m => Model.EmpCode) shows label correctly as Employee Code:

@Html.LabelFor(m => Model.PersonInfo.FName) shows label incorrectly as FName:

@Html.LabelFor(m => Model.PersonInfo.LName) shows label incorrectly as LName:

@Html.LabelFor(m => Model.PersonInfo.Department) shows label correctly as Department Name:

I am trying to figure out how do I show attribute information for object type properties. Do I have use extension methods?

Upvotes: 2

Views: 2891

Answers (2)

MarkG
MarkG

Reputation: 1869

You're using the wrong attribute. This simple example below works.

Controller:

public ActionResult Index()
{
    var model = new ParentModel {
        Name = "Parent name", 
        Child = new ChildModel {
            Name = "Child name"
        }
    };

    return View(model);
}

Models:

public class ParentModel
    {
        [DisplayName("Parent name:")]
        public string Name { get; set; }
        public ChildModel Child { get; set; }
    }

    public class ChildModel
    {
        [DisplayName("Child name:")]
        public string Name { get; set; }
    }

View:

@model ParentModel

@Html.LabelFor(model => model.Name)
@Html.LabelFor(model => model.Child.Name)

Upvotes: 6

kzhen
kzhen

Reputation: 3128

Is your person attribute null?

Try adding a default constructor in EmployeeViewModel and add

PersonInfo = new Person();

Upvotes: 0

Related Questions