这里您应该考虑两件事。第一个是尽量不要将表单放入部分视图中。如果这样做,您可能会得到浏览器不支持的嵌套表单,因为这不是有效的 HTML http://www.w3.org/TR/html401/interact/forms.html#h-17.3:
<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->
-(FORM)
构造不允许嵌套形式。
第二件事是代替部分观点我建议你使用编辑器模板. 看看这里 https://stackoverflow.com/questions/5197038/complex-models-and-partial-views-model-binding-issue-in-asp-net-mvc-3如何使用它们。接下来,正如我之前所说,尝试将表单保留在编辑器模板之外 - 在主视图中使用表单,并让编辑器模板呈现页面的不同部分。它将减少混乱并产生更清晰的代码。
在您的具体示例中,它可能如下所示:
主要观点:
@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)
{
...
Models:
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/
目录。