主控制器
public class TestPartialController : Controller
{
//
// GET: /TestPartial/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Main model)
{
HttpContext.Items.Add("MainModel", model);
return View();
}
public ActionResult PartialA()
{
return PartialView();
}
[HttpPost]
public ActionResult PartialA(PartialA a)
{
if (HttpContext.Items["MainModel"] != null)
{
Main model =(Main) HttpContext.Items["MainModel"];
model.PA = a;
}
return PartialView();
}
public ActionResult PartialB()
{
return PartialView();
}
[HttpPost]
public ActionResult PartialB(PartialB b)
{
if (HttpContext.Items["MainModel"] != null)
{
Main model = (Main)HttpContext.Items["MainModel"];
model.PB = b;
}
SubmitDatatoDB();
return PartialView();
}
public void SubmitDatatoDB()
{
if (HttpContext.Items["MainModel"] != null)
{
Main model = (Main)HttpContext.Items["MainModel"];
//SubmitDatatoDB
}
}
}
楷模:-
namespace TestingMVC4.Models
{
public class Main
{
public string Main1 { get; set; }
public string Main2 { get; set; }
public virtual PartialA PA { get; set; }
public virtual PartialB PB { get; set; }
}
public class PartialA
{
public string UserName { get; set; }
public string UserID { get; set; }
}
public class PartialB
{
public string UserNameB { get; set; }
public string UserIDB { get; set; }
}
}
看法 :-
@model TestingMVC4.Models.Main
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Main</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Main1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Main1)
@Html.ValidationMessageFor(model => model.Main1)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Main2)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Main2)
@Html.ValidationMessageFor(model => model.Main2)
</div>
<div>
@Html.Action("PartialA","TestPartial")
</div>
<div>
@Html.Action("PartialB","TestPartial")
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
@model TestingMVC4.Models.PartialA
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>PartialA</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.UserID)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserID)
@Html.ValidationMessageFor(model => model.UserID)
</div>
</fieldset>
}
我的问题是,如果这样做,主视图的 HTTPPOST 索引将首先触发。而不是跟随部分视图 A 和部分视图 B。在这种情况下,我需要将数据存储在 HttpContext.Items 中,并在最后一个部分视图 B 中调用提交到数据库。
我想要的是首先触发部分视图 A 和 B,并将数据存储到主视图的模型中,并在主视图的 POST 操作中调用 SubmitDatatoDB 函数。