In my MVC5 application I have an enum class as shown below and with this approach I can pass the enum values i.e. US, UK instead of United States" from Controller to View. How can I pass and display enum description with the following approach? I tried many different solution method as C# String enums, etc. but none of them solved my problem. On the other hand, I do not want to use sealed class and it would be better for me a solution with enum class as shown below:
Enum:
public enum Country
{
[Description("United States")]
US = 1,
[Description("United Kingdom")]
UK = 2,
[Description("New Zealand")]
NewZealand = 3,
[Description("France")]
France = 4,
[Description("Germany")]
Germany = 5
}
Model:
public class VisitorViewModel
{
[Key]
public int VisitorID { get; set; }
public Country Country { get ; set; }
//code omitted for brevity
}
Controller:
public JsonResult Visitor_Read([DataSourceRequest] DataSourceRequest request)
{
var result = db.Visitors.Select(m => new VisitorViewModel
{
VisitorID = m.VisitorID,
Country = m.Country
//code omitted for brevity
})
var jsonResult = Json(result, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
View:
$(document).ready(function () {
var grid = $("#visitorGrid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "/Visitor/Visitor_Read",
dataType: "json",
cache: false
}
},
schema: {
model: {
fields: {
VisitorID: { type: 'number' },
Country : { type: 'string' }
}
}
}
},
columns:
[
{ field: "VisitorID", title: "Id" },
{ field: "Country ", title: "Country" },
]
}).data("kendoGrid");
});
See Question&Answers more detail:os