ASP.NET MVC3 WebGrid 帮助程序和模型元数据
我正在尝试使用 ASP.NET MVC 3 中的 WebGrid html 帮助程序根据 ModelMetadata 中找到的信息自动生成列。例如,接受对象列表的视图中的代码将是:
var grid = new WebGrid(Model);
@grid.GetHtml(columns: ViewData.ModelMetadata.Properties.Single.Properties
.Select(p => grid.Column(
columnName: p.PropertyName,
header: p.ShortDisplayName
)));
这实际上就像一个魅力(我很惊讶它实际上如此简单)。这里发生的情况是,从模型的属性中,我使用 ShortDisplayName 作为列的标题。
问题?我需要对所有列应用默认格式。基本上我想对网格将显示的所有数据使用 Html.Raw 扩展。尝试是这样的:
var grid = new WebGrid(Model);
@grid.GetHtml(columns: ViewData.ModelMetadata.Properties.Single.Properties
.Select(p => grid.Column(
columnName: p.PropertyName,
header: p.ShortDisplayName,
format: (item) => Html.Raw(GetPropertyValue(item, p.PropertyName))
)));
方法 GetPropertyValue 将使用反射或其他方式读取属性的值(我需要提醒这里,项目是动态的,它的值实际上是当前行中显示的对象)。
有没有更好的方法来做到这一点?
谢谢,
科斯塔斯
I'm trying to use the WebGrid html helper in ASP.NET MVC 3 to autogenerate the columns according to the information found in the ModelMetadata. For example the code in a view that accepts a list of objects would be:
var grid = new WebGrid(Model);
@grid.GetHtml(columns: ViewData.ModelMetadata.Properties.Single.Properties
.Select(p => grid.Column(
columnName: p.PropertyName,
header: p.ShortDisplayName
)));
This actually works like a charm (I was surprised it was that easy actually). What happens here is that from the properties of the model I use the ShortDisplayName as the column's header.
The problem? I need to apply a default format to all columns. Basically I want to use the Html.Raw extension for all the data that my grid will display. An attempt would be something like that :
var grid = new WebGrid(Model);
@grid.GetHtml(columns: ViewData.ModelMetadata.Properties.Single.Properties
.Select(p => grid.Column(
columnName: p.PropertyName,
header: p.ShortDisplayName,
format: (item) => Html.Raw(GetPropertyValue(item, p.PropertyName))
)));
where the method GetPropertyValue would read the value of the property using reflection or whatever (I need to remind here that item is dynamic and its value is actually the object that is being displayed in the current row).
Is there any better way to do this?
Thanks,
Kostas
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您研究 MVCContrib Grid 项目: http://mvccontrib.codeplex.com/wikipage?title=网格
I suggest you looking into MVCContrib Grid project: http://mvccontrib.codeplex.com/wikipage?title=Grid
不知道您是否仍然需要一些帮助来解决这个问题,但我遇到了和您一样的问题,这就是我解决它的方法:
我得到的代码是这样的:
这就是我获取属性值的方式:
我真的不知道这是否是最好的方法,但它对我来说效果很好。
Don't know if you still need some help with this question, but I had a problem just like yours and that's what I did to solve it:
The code that I got was something like this:
And that's how I get the property's value:
I really don't know if this is the best way, but it's working pretty good for me.