In an MVC 5
app, I need to get an Enums's Display Name
attributes as a list. I can use the Enum.GetNames()
to get the names no problem, but can't figure out how to implement something like Enum.GetDisplayName(). I've tried extension methods and searched the web, but no success yet.
How can I do this?
This is not a duplicate of this:
How to get the Display Name Attribute of an Enum member via MVC razor code? 9 answers
Controller:
public JsonResult GetCategoryDescriptions(int id)
{
var category = (Category)id;
switch (category)
{
case Category.Claim:
return Json(Enum.GetNames(typeof(Claim)).ToList(),JsonRequestBehavior.AllowGet);
case Category.Commissions:
return Json(Enum.GetNames(typeof(Commissions)).ToList(), JsonRequestBehavior.AllowGet);
default:
return null;
}
}
View/JQuery:
$("#category").change(function () {
if ($("#category").val() != "Select") {
var val = $("#category").val();
$.ajax({
url: "@Url.Action("GetCategoryDescriptions","Call", new {area = "", id = "_id_"})".replace("_id_", val),
type:"GET",
datatype:"json",
contentType:"application/json"
}).done(function (descriptions) {
$("#categoryDescription").empty();
$("#categoryDescription").append("<option> Select </option>");
for (var i = 0; i < descriptions.length; i++) {
$("#categoryDescription").append("<option>" + descriptions[i] + "</option>");
}
}).fail(function(jqXHR, textStatus){
alert("Error getting Category Descriptions");
});
}
else {
$("#categoryDescription").empty();
$("#categoryDescription").prop("disabled", true);
}
});
Viewmodel/Class:
public enum Claim
{
[Display(Name = "Benefit Verification")]
BenefitVerification,
[Display(Name = "Claim Appeal")]
ClaimAppeal
}