我正在尝试创建一个复制
Html.EditorForModel()的通用编辑器模板,以便以后自定义和构建.
Brad Wilson’s template变得非常接近,但我发现当ViewData(或ViewBag)和模型中存在相同的密钥时,它会窒息.例如,如果视图模型也具有Title属性,则ViewBag.Title会导致问题.
我学习了here,使用强类型助手(即Html.EditorFor(x => x.Title)而不是Html.Editor(“Title”)似乎有所帮助.所以我试图修改Brad的模板,但我遇到了砖墙,因为到目前为止我没有尝试过任何工作.我无法弄清楚如何在我不知道模型类型的上下文中使用强类型帮助器,例如编辑器模板.
有没有办法像Brad那样创建一个Object模板,但是使用强类型的助手(即LabelFor,EditorFor,ValidatorMessageFor)而不是弱类型的助手(即Label,Editor,ValidatorMessage)?
谢谢.
解决方法
我通过稍微迂回的方式解决了这个问题,方法是在调用@Html.Editor之前删除ViewData,然后再将其放回去.
Object.cshtml:
object oldViewData = null; var hasConflictingViewData = ViewData.TryGetValue(prop.PropertyName,out oldViewData); if (hasConflictingViewData) { ViewData.Remove(prop.PropertyName); } @Html.Editor(prop.PropertyName) if (hasConflictingViewData) { ViewData.Add(prop.PropertyName,oldViewData); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。