Tuesday, November 24, 2015

ASP.Net MVC: Display custom, dynamically queried field names

Controller Method

public ActionResult Contact()
{
return View(new ContactViewModel()
{
MarketingEmail = "marketing@example.com",
SupportEmail = "support@example.com"
});
}

ViewModel

public class ContactViewModel
{
        [Display(Name="SupportEmailLabel", ResourceType=typeof(CustomFieldNames))]
        public String SupportEmail { get; set; }

        [Display(Name = "MarketingEmailLabel", ResourceType = typeof(CustomFieldNames))]
        public String MarketingEmail { get; set; }

}

Field Name Provider Class

static public class CustomFieldNames
{
static public string SupportEmailLabel
{
get
{
// This label can be retrieved from the database or application cache
// The label can be varied by each user
return "Help email address";
}
}

static public string MarketingEmailLabel
{
get
{
return "Marketing email address";
}
}
}

View

@model MvcWebAppCustomFieldNames.Models.ContactViewModel
@{
    ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title</h2>

<address>
    <strong>@Html.LabelFor(m => m.SupportEmail):</strong>   <a href="mailto:@Model.SupportEmail">@Model.SupportEmail</a><br />
    <strong>@Html.LabelFor(m => m.MarketingEmail):</strong> <a href="mailto:@Model.MarketingEmail">@Model.MarketingEmail</a>
</address>

Output