1

I'm working with ASP.NET MVC4.

I am looking to change the display name of a property based on some other value retrieved from a database, so that when I call @Html.LabelFor() in my view, the correct field text is displayed.

The example I'm working with uses an Address View Model, with different properties for each line of the address. If the address is US, then one of the fields should say 'State'. If it's a UK address, it should say 'County'. Same applied for 'Zip Code' and 'Post Code'.

Obviously I don't want different Properties for each different field for each country.

I also what to apply a different regular expression validation rule for the Postal Code depending on the country. How can I also do this?

Here's my class at the moment:

public class AddressViewModel
{
    public Guid Id { get; set; }

    [Display(Name = "Address_Country", ResourceType = typeof(Resources.Shared))]
    [Required]
    public Guid CountryId { get; set; }

    [Display(Name = "Address_AddressLine1", ResourceType = typeof(Resources.Shared))]
    public string AddressLine1 { get; set; }

    [Display(Name = "Address_AddressLine2", ResourceType = typeof(Resources.Shared))]
    public string AddressLine2 { get; set; }

    [Display(Name = "Address_AddressLine3", ResourceType = typeof(Resources.Shared))]
    public string AddressLine3 { get; set; }

    [Display(Name = "Address_AddressLine4", ResourceType = typeof(Resources.Shared))]
    public string AddressLine4 { get; set; }

    [Display(Name = "Address_AddressLine5", ResourceType = typeof(Resources.Shared))]
    public string AddressLine5 { get; set; }

    [Display(Name = "Address_PostalCode", ResourceType = typeof(Resources.Shared))]
    public string PostalCode { get; set; } 
}

Any help would be greatly received.

Thanks.

Adam Young
  • 1,217
  • 10
  • 18
  • Check out the Yngve B. Nilsen's approach, http://stackoverflow.com/questions/3446893/how-to-change-displaynamexxx-in-controller – caner Jun 10 '13 at 13:48
  • It did find this article, but it's not quite what I need. I need to pass the Country Id into the display attribute. I've only added the CountryCodeId into this example to give it some meaning. The actual country code is retrieved in the controller. I some how need to retrieve the address model, and then update the display names in the controller on a per-request basis. – Adam Young Jun 10 '13 at 14:00
  • So the CountryId is read-only (it is set only in controller), or is it somewhere in drop-down (user can change this model property) ? – Ondrej Svejdar Jun 10 '13 at 16:09

0 Answers0