asp.net-mvc 发布具有多个局部视图的表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10608766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:56:33  来源:igfitidea点击:

Post a form with multiple partial views

asp.net-mvcasp.net-mvc-3razorhttp-postpartial-views

提问by dalcantara

I'm currently trying to post a form composed of two strongly typed views. This question is similar but it doesn't have an answer:

我目前正在尝试发布一个由两个强类型视图组成的表单。这个问题很相似,但没有答案:

MVC 3 Razor Form Post w/ Multiple Strongly Typed Partial Views Not Binding

MVC 3 Razor Form Post w/多个强类型部分视图未绑定

When I submit form the model submitted to the controller is always null. I've spent a couple of hours trying to get this to work. This seems like it should be simple. Am I missing something here? I don't need to do ajax just need to be able to post to the controller and render a new page.

当我提交表单时,提交给控制器的模型始终为空。我花了几个小时试图让它发挥作用。这看起来应该很简单。我在这里错过了什么吗?我不需要做 ajax 只需要能够发布到控制器并呈现一个新页面。

Thanks

谢谢

Here's my view code:

这是我的视图代码:

<div>
    @using (Html.BeginForm("TransactionReport", "Reports", FormMethod.Post, new {id="report_request"}))
    {
        ViewContext.FormContext.ValidationSummaryId = "valSumId";
        @Html.ValidationSummary(false, "Please fix these error(s) and try again.", new Dictionary<string, object> { { "id", "valSumId" } });
        @Html.Partial("_ReportOptions", Model.ReportOptions);
        @Html.Partial("_TransactionSearchFields", new ViewDataDictionary(viewData) { Model = Model.SearchCriteria });
    }

Here's the code in the controller:

这是控制器中的代码:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TransactionReport(TransactionReportRequest reportRequest)
{
    var reportInfo = new List<TransactionReportItem>();

    if (ModelState.IsValid)
    {
        var reportData = _reportDataService.GetReportData(Search.MapToDomainSearchCriteria(reportRequest.SearchCriteria));
        if (reportData!=null)
        {
            reportInfo = reportData.ToList();
        }
        return View(reportInfo);
    }
    return View(reportInfo);
}

The partial views themselves are pretty irrelevant since all they are doing is biding and displaying their models.

部分视图本身是无关紧要的,因为它们所做的只是投标和展示它们的模型。

回答by Styxxy

Partials are not the way to go here. You are looking for EditorTemplates, these are made for what you want. This case, your properties will be nicely bound to your model (that you will submit).

部分不是去这里的方式。您正在寻找 EditorTemplates,它们是为您想要的而制作的。在这种情况下,您的属性将很好地绑定到您的模型(您将提交)。

Your main View will have this form (note that you only have to use EditorForinstead of Partial; in this case, you probably will need to put that viewData parameter in the ViewBag or so):

您的主视图将具有这种形式(请注意,您只需使用EditorFor代替Partial;在这种情况下,您可能需要将该 viewData 参数放在 ViewBag 左右):

@using (Html.BeginForm("TransactionReport", "Reports", FormMethod.Post, new {id="report_request"}))
{
    ViewContext.FormContext.ValidationSummaryId = "valSumId";
    @Html.ValidationSummary(false, "Please fix these error(s) and try again.", new Dictionary<string, object> { { "id", "valSumId" } });
    @Html.EditorFor(model => model.ReportOptions);
    @Html.EditorFor(model = Model.SearchCriteria });
}

Now you only have to drag your partials to the folder ~/Shared/EditorTemplates/and rename them to match the model name they are the editor templates for.

现在您只需将您的部分拖到文件夹中~/Shared/EditorTemplates/并重命名它们以匹配它们作为编辑器模板的模型名称。

In the ~/Shared/EditorTemplates/folder, make a new "view", example "SearchCriteria.cshtml". Inside, put as "model" the type of class you which to create an editor template for. Example (example class has properties Nameand OtherCriteria):

~/Shared/EditorTemplates/文件夹中,创建一个新的“视图”,例如“SearchCriteria.cshtml”。在里面,将要为其创建编辑器模板的类的类型作为“模型”。示例(示例类具有属性NameOtherCriteria):

@model MyNamespace.SearchCriteria
<ul>
    <!-- Note that I also use EditorFor for the properties; this way you can "nest" editor templates or create custom editor templates for system types (like DateTime or String or ...). -->
    <li>@Html.LabelFor(m => m.Name): @Html.EditorFor(m => m.Name)</li>
    <li>@Html.LabelFor(m => OtherCriteria): @Html.EditorFor(m => m.OtherCriteria</li>
</ul>

Some good reading about them:

关于它们的一些很好的阅读:

回答by Sebastian Xawery Wi?niowiecki

You should add prefix to the PartialView's fields. That will let binding data correctly.

您应该为 PartialView 的字段添加前缀。这将使绑定数据正确。

So instead:

所以与其:

@Html.Partial("_ReportOptions", Model.ReportOptions);

Use:

用:

@Html.Partial("_ReportOptions", Model.ReportOptions, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "ReportOptions" }})

回答by Erik Funkenbusch

I agree with @Styxxy and @Tony, Editor Templates are the better solution. However, your problem is that that you are feeding a sub-model to the partial views. Thus, when the partial view renders it doesn't know that it's part of a larger model and does not generate the correct name attributes.

我同意 @Styxxy 和 @Tony,编辑器模板是更好的解决方案。但是,您的问题是您正在向局部视图提供子模型。因此,当局部视图呈现时,它不知道它是更大模型的一部分,并且不会生成正确的名称属性。

If you insist on using Partials rather than Editor Templates, then I suggest only passing the Model to the partials, then having each partial do Model.Whatever.Foo and it will generate the correct name attributes for binding.

如果您坚持使用 Partials 而不是 Editor Templates,那么我建议只将 Model 传递给 partials,然后让每个 Partial 执行 Model.Whatever.Foo,它将生成正确的名称属性以进行绑定。

回答by magritte

Try using EditorTemplates instead of Partials http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/.

尝试使用 EditorTemplates 而不是 Partials http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

回答by Kesikan K

@Html.Partial("_ReportOptions", Model.Contact, new ViewDataDictionary()
           {
               TemplateInfo = new TemplateInfo()
                   {
                       HtmlFieldPrefix = "Contact"
                   }
           })

)


@Html.Partial("_TransactionSearchFields", Model.SearchCriteria, new  
 ViewDataDictionary()
           {
               TemplateInfo = new TemplateInfo()
                   {
                       HtmlFieldPrefix = "SearchCriteria"
                   }
           })