【发布时间】:2016-03-21 11:51:35
【问题描述】:
在我的 MVC5 应用程序中,我有一个枚举类,如下所示,通过这种方法,我可以将枚举值(即美国、英国而不是美国)从 Controller 传递到 View。如何通过以下方式传递和显示枚举描述方法?我尝试了许多不同的解决方法,如C# String enums 等,但没有一个能解决我的问题。另一方面,我不想使用密封类,对我来说,使用枚举类的解决方案会更好,如图所示下面:
枚举:
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
}
型号:
public class VisitorViewModel
{
[Key]
public int VisitorID { get; set; }
public Country Country { get ; set; }
//code omitted for brevity
}
控制器:
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;
}
查看:
$(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");
});
【问题讨论】:
-
如果您使用的是 asp.net MVC,为什么不使用 razor 创建网格?
-
您可以添加额外的getter
public string CountryName,返回Country.ToString() -
@ataravati 我用的是razor(查看页面是cshtml)。如果你是说 Kendo MVC,我以前用过,但在这个项目中,出于某种原因,我不得不在 javascript 中使用 Kendo Grid。另一方面,解决这个问题有意义吗?因为首先我需要将由多个单词组成的字符串值从控制器返回到视图。至少对此有任何想法吗?
-
@GeneR 但是我使用 EF Code First 方法,我不确定向相关实体类添加新属性是否会导致数据库中出现额外的列。我应该将它用作虚拟吗?您可以通过更改我的原始代码来发布示例吗?
-
@Christof 我首先使用 EF 逆向工程代码,并为模型生成
partial class,然后为模型自定义属性创建相同的partial class
标签: asp.net-mvc enums kendo-ui kendo-grid kendo-asp.net-mvc