繁体   English   中英

MVC4:嵌套的部分视图丢失模型数据

[英]MVC4: nested partial-view loses model data

在MVC4项目中,我使用部分视图,即使用ViewModel并在其上具有GET Form。 在Controller动作中,我希望ViewModel对象包含一些数据。 当此部分放置在普通(.cshtml)视图上时,我通过Controller操作中的预期ViewModel对象接收了数据。 但是,当将此部分放置在另一个部分视图上时 ,由于某种原因,控制器操作中的ViewModel对象为空。 当我逐步完成HttpGet表单的创建时,传入的模型并不为空,但是当调用GET控制器操作时,该模型为空。

有人知道原因吗? 这是我不知道的某些MVC行为吗? 谢谢!

部分:

@model ViewModel
    @if (Model != null)
    {
        using (Html.BeginForm("DoSomething", "Home", FormMethod.Get))
        { 
            @Html.HiddenFor(m => m.Object)            
            <input id="btnSend" type="submit"> 
        }
    }

其他部分:

@using OtherViewModel.ViewModel
@Html.Partial("The Partial", Model.ViewModel, ViewData)

风景:

@Html.Partial("_TheOtherPartial", Model.OtherViewModel, new ViewDataDictionary(ViewData) {
                TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "prefix" }
    })

控制器

[HttpGet]
[AllowAnonymous]
public ActionResult DoSomething(ViewModel data)
{
}

这里有两件事您应该考虑。 第一种是尽量不要将表单放在部分视图中 如果这样做,最终可能会导致嵌套表单,浏览器不支持嵌套表单,因为它不是有效的HTML

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->

-(FORM)构造不允许嵌套形式。

第二件事是代替部分视图,我建议您使用编辑器模板 在这里看看如何使用它们。 接下来,正如我之前所说,尝试将表单保留在编辑器模板之外-在主视图中使用表单,并让编辑器模板呈现页面的不同部分。 它将减少混乱,并产生更清晰的代码。

在您的特定示例中,它可能如下所示:

主要观点:

@model MainModel
@using (Html.BeginForm("YourAction", "YourController"))
{ 
    @Html.EditorFor(m => m.OtherViewModel)
    <input id="btnSend" type="submit"> 
}

OtherViewModel.cshtml编辑器模板:

@model OtherViewModel
@Html.EditorFor(m => m.ViewModel)

ViewModel.cshtml编辑器模板:

@model ViewModel
@Html.EditorFor(m => m.Object)

主控制器:

public ActionResult YourAction(MainModel data)
{
    ...

楷模:

public class MainModel
{
    public MainModel() { OtherViewModel = new OtherViewModel(); }
    public OtherViewModel OtherViewModel { get; set; }        
}

public class OtherViewModel
{
    public OtherViewModel() { ViewModel = new ViewModel(); }
    public ViewModel ViewModel { get; set; }
}

public class ViewModel
{
    public string Object { get; set; }
}

请注意,模板名称反映了模型类型名称。 接下来,将您的模板放在此~/Views/Shared/EditorTemplates/或此~/Views/YourController/EditorTemplates/目录下。

或者,您可以将与在“视图”中获得的原始模型相同的模型传递给“其他部分”,然后再次传递给“部分”,同时仅使用所需部分的相应视图。

暂无
暂无

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

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