好,将数据发送到控制器操作通常通过对此控制器操作执行HTTP请求来完成。有执行HTTP请求的方式不同:
- 使用
<form>
标签指向这个动作
- 使用AJAX
所以,如果你用第一种方法去,你可以有一个<form>
包装所有的部分将有多个提交按钮(具有不同的名称)。然后当你点击一个提交按钮时,所有的输入字段将被发送到控制器动作,然后在控制器动作中,你可以基于哪个提交按钮被点击来处理数据。
如果您使用第二个选项,那么只需收集您需要发送的按钮点击按钮并将它们沿着AJAX请求发送。
UPDATE:
正如在评论部分要求在这里是如何的第一个技术可以付诸行动。它使用两个部分而不是三个,但它可以很容易地外推。
与往常一样开始通过定义将代表数据的视图模型,你想在这个特别的观点一起工作:
public class MyViewModel
{
public Partial1ViewModel Model1 { get; set; }
public Partial2ViewModel Model2 { get; set; }
}
public class Partial1ViewModel
{
public string Foo { get; set; }
}
public class Partial2ViewModel
{
public string Bar { get; set; }
}
然后控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Model1 = new Partial1ViewModel { Foo = "foo" },
Model2 = new Partial2ViewModel { Bar = "bar" },
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
// Here you have access to model.Model1.Foo and model.Model2.Bar =>
var button = "";
if (!string.IsNullOrEmpty(Request["submit1"]))
{
// submit1 button was used
button = "submit1";
}
else if (!string.IsNullOrEmpty(Request["submit2"]))
{
// submit2 button was used
button = "submit2";
}
var result = string.Format("thanks for submitting using {0}", button);
return Content(result, "text/plain");
}
}
然后主视图(~/Views/Home/Index.cshtml
):
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Model1)
@Html.EditorFor(x => x.Model2)
}
和两个相应的edito [R模板(或谐音如果你愿意):
~/Views/Home/EditorTemplates/Partial1ViewModel.cshtml
:
@model Partial1ViewModel
<h2>Partial 1</h2>
<div>
@Html.LabelFor(x => x.Foo)
@Html.EditorFor(x => x.Foo)
<input type="submit" value="Submit me!" name="submit1" />
</div>
~/Views/Home/EditorTemplates/Partial2ViewModel.cshtml
:
@model Partial2ViewModel
<h2>Partial 2</h2>
<div>
@Html.LabelFor(x => x.Bar)
@Html.EditorFor(x => x.Bar)
<input type="submit" value="Submit me!" name="submit2" />
</div>
u能提供例如如何实现此 – 2011-06-17 11:26:27