将值从部分视图提交到父视图模型

时间:2012-04-17 03:12:24

标签: c# asp.net-mvc-3 partial-views

假设我有一个包含复选框和数值的局部视图。 我有一个ViewModel,它包含一个模型 - 术语 - 实现局部视图。当我提交时,条款部分视图中所做的修改不会反映在ViewModel的Terms属性中。我可能误解了一个或另一个关于它是如何工作的概念,有人想指出它吗?

查看

@model ViewModel
@using (Html.BeginForm("ViewAction", "ViewController", FormMethod.Post))
{
 // Other ViewModel Property Editors

 @Html.Partial("Terms", Model.Terms)
 <input type="submit" value="Submit" />
}

部分视图

@model Terms

@Html.CheckBoxFor(m => m.IsAccepted)
@Html.EditorFor(m => m.NumericalValue)

控制器

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult ViewAction(int id)
{
 ViewModel vm = GetVmValues();
 return View(vm);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ViewAction(ViewModel vm)
{
 // Access ViewModel properties
}

2 个答案:

答案 0 :(得分:1)

默认型号装订器需要将您的条款模型的控件ID命名为Terms.IsAcceptedTerms.NumericalValue。您需要为Terms模型创建一个编辑器模板,然后调用@Html.EditorFor(m=> m.Terms)而不是使用部分模型。

您可以阅读有关编辑器模板here的更多信息。它来自MVC 2,但仍然应该是相关的。

答案 1 :(得分:0)

将部分视图的模型类型更改为“ViewModel”而不是“条款”。 这是更新的代码:

查看:

@model ViewModel
@using (Html.BeginForm("ViewAction", "ViewController", FormMethod.Post))
{
 // Other ViewModel Property Editors

 @Html.Partial("Terms", Model)  //Set parent 'ViewModel' as model of the partial view
 <input type="submit" value="Submit" />
}

部分视图:

@model ViewModel

@Html.CheckBoxFor(m => m.Terms.IsAccepted)
@Html.EditorFor(m => m.Terms.NumericalValue)

生成的Html将是:

<input id="Terms_IsAccepted" name="Terms.IsAccepted" type="checkbox" value="true">

当来自值提供者的DefaultModelBinder映射值(例如表单数据/路由数据/ query-stirng / http文件)到复杂对象时,它会搜索具有该名称作为对象属性的值。在您的情况下,要构建“ViewModel”的“Terms”子对象,它将搜索名称为“Terms.IsAccepted”,“Terms.NumericalValue”等的值。 Html帮助器使用属性路径表达式来生成html元素的名称,这就是为什么必须使用父ViewModel作为局部视图的模型。

希望这会有所帮助......

相关问题