简体   繁体   English

ASP.NET MVC-使用部分视图与TemplateInfo时缺少错误消息

[英]ASP.NET MVC - Missing Error Messages using Partial View with TemplateInfo

I have an ASP.NET ViewModel like this: 我有一个像这样的ASP.NET ViewModel:

public class ParentViewModel
{
    public ChildViewModel Child { get; set; }
}

The ChildViewModel class in turn has properties that are decorated with the Required attribute and an appropriate error message. 反过来,ChildViewModel类具有用Required属性和适当的错误消息修饰的属性。 The reason for having a ViewModel set up like this is because the ChildViewModel is tied to a partial view and the partial view is rendered in different contexts. 之所以要这样设置ViewModel,是因为ChildViewModel绑定到局部视图,并且局部视图在不同的上下文中呈现。 In one context, I am rendering the ChildViewModel's partial view as such: 在一种情况下,我正在这样渲染ChildViewModel的局部视图:

@Html.Partial("~/Views/Shared/_ChildView.cshtml", Model.AddressModel, new ViewDataDictionary
   {
       TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Child" },                   
   })

The TemplateInfo causes the HTML inputs for the partial view to render with the correct name so they are correctly repopulated into the ParentViewModel on post back. TemplateInfo使部分视图的HTML输入以正确的名称呈现,因此在回发时将它们正确地重新填充到ParentViewModel中。 ASP.Net is also correctly detecting when the child view model is missing information (ModelState.IsValid returns the correct result). ASP.Net还可以正确检测子视图模型何时缺少信息(ModelState.IsValid返回正确的结果)。 However, the problem is it does not display the validation error messages. 但是,问题是它不显示验证错误消息。 Any ideas on how to get the error messages to show? 关于如何显示错误消息的任何想法?

Why don't you use editor templates? 为什么不使用编辑器模板? I mean the following looks horrible: 我的意思是以下内容看起来很可怕:

@Html.Partial("~/Views/Shared/_ChildView.cshtml", Model.AddressModel, new ViewDataDictionary
{
    TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Child" },                   
})

Not only that it looks horrible but it might exhibit some side effects as you have already found out. 正如您已经发现的那样,它不仅看起来可怕,而且可能会显示一些副作用。

How about: 怎么样:

@Html.EditorFor(x => x.Child)

Cleaner, isn't it? 清洁一点,不是吗? Now all you have to do is to move ~/Views/Shared/_ChildView.cshtml into ~/Views/Shared/EditorTemplates/ChildViewModel.cshtml : 现在,您要做的就是将~/Views/Shared/_ChildView.cshtml移到~/Views/Shared/EditorTemplates/ChildViewModel.cshtml

@model ChildViewModel
...

This is all really the wrong way to go about this. 这确实是错误的解决方法。 Instead of Partial views, you should be using Templates. 您应该使用模板而不是部分视图。

If you create a Child.cshtml and put it in DisplayTemplates (or EditorTemplates if it's an editor)Then, in your code you can simply do this: 如果创建Child.cshtml并将其放入DisplayTemplates(如果是编辑器,则将其放入EditorTemplates),然后在代码中只需执行以下操作:

@Html.DisplayFor(m => m.Child)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM