使用ViewBag Html.Display - 对象模板 [英] Object template - Html.Display using ViewBag
问题描述
我有以下对象显示模板(<一个href=\"http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html\"相对=nofollow>来源):
@model对象@if(型号== NULL){
@ ViewData.ModelMetadata.NullDisplayText
}否则如果(ViewData.TemplateInfo.TemplateDepth→1){
@ ViewData.ModelMetadata.SimpleDisplayText
}其他{
的foreach(; pm.ShowForDisplay和放大器;在ViewData.ModelMetadata.Properties.Where(PM =&GT VAR道具和放大器;!ViewData.TemplateInfo.Visited(PM))){
如果(prop.HideSurroundingHtml){
@ Html.Display(prop.PropertyName)
}其他{
&LT; DIV&GT;
&LT;强&GT; @ prop.GetDisplayName():其中; / STRONG&GT; @ Html.Display(prop.PropertyName)
&LT; / DIV&GT;
}
}
}
伟大的工程,直到有在 ViewBag
相同的密钥。对于下面的类例如:
公共类文章{
公共字符串名称{搞定;组; }
公共字符串文本{搞定;组; }
}
应该显示(将空ViewBag显示)
标题:真棒称号
文字:真棒文本
但它显示的时候 ViewBag.Title
设置为详细信息
标题:详细
文字:真棒文本
这是由 @ Html.Display(prop.PropertyName)引起的
,似乎preFER ViewBag
对模型值的价值。有什么建议么?我不能使用 Html.DisplayFor
,因为我只属性名称存储在字符串变量,还不如前pression为给定的模型。
我想我可以明确viewbag并在以后恢复它,但这并不像很好的解决方案给我。
编辑:查看看起来是这样的:
@model文章@ {
ViewBag.Title =详细信息;
}@ Html.DisplayForModel()
找到解决方案:的 http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx - @ Html.DisplayFor(M = GT; prop.Model)
按预期工作。谁知道有模式
中的元数据属性。
I've got following display template for object (source):
@model object
@if (Model == null) {
@ViewData.ModelMetadata.NullDisplayText
} else if (ViewData.TemplateInfo.TemplateDepth > 1) {
@ViewData.ModelMetadata.SimpleDisplayText
} else {
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForDisplay && !ViewData.TemplateInfo.Visited(pm))) {
if (prop.HideSurroundingHtml) {
@Html.Display(prop.PropertyName)
} else {
<div>
<strong>@prop.GetDisplayName():</strong> @Html.Display(prop.PropertyName)
</div>
}
}
}
Which works great, until there is same key in ViewBag
. For example following class
public class Article {
public string Title { get; set; }
public string Text { get; set; }
}
should display (and will display with empty ViewBag)
Title: Awesome title
Text: Awesome text
however it displays following when ViewBag.Title
is set to "Detail"
Title: Detail
Text: Awesome text
It is caused by @Html.Display(prop.PropertyName)
that seem to prefer ViewBag
value against model value. Any suggestions? I can't use Html.DisplayFor
because I have only property name stored in string variable, not as expression for given model.
I guess I could clear viewbag and restore it later, but that doesn't look like good solution to me.
Edit: View looks like this:
@model Article
@{
ViewBag.Title = "Detail";
}
@Html.DisplayForModel()
Found solution: http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx - @Html.DisplayFor(m => prop.Model)
works as expected. Who knew there was Model
property in metadata..
这篇关于使用ViewBag Html.Display - 对象模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!