MVC DisplayFor函数-我如何找出哪个模板被使用
本文关键字:何找出 函数 DisplayFor MVC | 更新日期: 2023-09-27 18:16:18
我有以下问题:
@Html.DisplayFor(m => m.PkID)
(PkID是long类型)失败,有以下例外:
[InvalidOperationException: The model item passed into the dictionary is of type 'System.Int64', but this dictionary requires a model item of type 'System.String'.]
System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +378
System.Web.Mvc.ViewDataDictionary.set_Model(Object value) +47
System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +614
System.Web.Mvc.ViewDataDictionary`1..ctor(ViewDataDictionary viewDataDictionary) +37
System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +98
System.Web.Mvc.WebViewPage.set_ViewData(ViewDataDictionary value) +39
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +425
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.Html.TemplateHelpers.ExecuteTemplate(HtmlHelper html, ViewDataDictionary viewData, String templateName, DataBoundControlMode mode, GetViewNamesDelegate getViewNames, GetDefaultActionsDelegate getDefaultActions) +1037
System.Web.Mvc.Html.TemplateHelpers.TemplateHelper(HtmlHelper html, ModelMetadata metadata, String htmlFieldName, String templateName, DataBoundControlMode mode, Object additionalViewData, ExecuteTemplateDelegate executeTemplate) +1621
System.Web.Mvc.Html.TemplateHelpers.TemplateHelper(HtmlHelper html, ModelMetadata metadata, String htmlFieldName, String templateName, DataBoundControlMode mode, Object additionalViewData) +94
System.Web.Mvc.Html.TemplateHelpers.TemplateFor(HtmlHelper`1 html, Expression`1 expression, String templateName, String htmlFieldName, DataBoundControlMode mode, Object additionalViewData, TemplateHelperDelegate templateHelper) +225
System.Web.Mvc.Html.TemplateHelpers.TemplateFor(HtmlHelper`1 html, Expression`1 expression, String templateName, String htmlFieldName, DataBoundControlMode mode, Object additionalViewData) +140
System.Web.Mvc.Html.DisplayExtensions.DisplayFor(HtmlHelper`1 html, Expression`1 expression) +92
我们有很多的DisplayTemplates和EditorTemplates在我们的项目中,我确信其中一个是使用而不是默认的,但我需要知道哪个模板被选择(不正确),以便我可以修复内容。
如何知道框架选择了哪个模板?在Visual Studio 2013中使用调用堆栈没有帮助,因为我只得到反编译的汇编代码,该方法将具有模板名称(System.Web.Mvc.Html.TemplateHelpers.ExecuteTemplate)。
在Visual Studio中,转到Tools > Options > Debugging
并取消选中Step over properties and operators (Managed Only)
在@Html.DisplayFor(m => m.PkID)
上添加断点。它可能会出现在很多其他东西中但最终会出现在模板
对我来说,确定执行哪个模板的最佳方法是了解在MVC框架中如何处理显示和编辑器模板。只有几个不同的选项,你应该检查
- 你在DisplayFor调用中明确指定了模板名(这不是你的情况下的选项)
- 你在
PkID
上使用UIHintAttribute来指示框架使用哪个模板 - 在Views/ControllerName/DisplayTemplates下有模板
- 你有一个模板放置在Views/Shared/DisplayTemplates
请注意,即使模板被放置在物理位置,但排除在visual studio解决方案之外,它仍然会被渲染。