View视图代码:
@model MyViewModel
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
@Html.LabelFor(model => model.MasterProperty)
@Html.EditorFor(model => model.MasterProperty)
// Detail视图表格
@foreach(var detail in Model.DetailList)
{
@Html.LabelFor(model => detail.DetailProperty1, detail.Id.ToString())
@Html.HiddenFor(model => detail.Id)
@Html.EditorFor(model => detail.DetailProperty1)
@Html.ValidationMessageFor(model => detail.DetailProperty1)
@Html.LabelFor(model => detail.DetailProperty2)
@Html.EditorFor(model => detail.DetailProperty2)
@Html.ValidationMessageFor(model => detail.DetailProperty2)
}
}
ViewModel代码:
public class DetailViewModel
{
public int Id { get; set; }
public string DetailProperty1 { get; set; }
public string DetailProperty2 { get; set; }
}
public class MyViewModel
{
public string MasterProperty { get; set; }
public List DetailList { get; set; }
}
Controller代码:
public class MyController : Controller
{
[HttpPost]
public ActionResult ActionName(MyViewModel viewModel)
{
// Save MasterData
var masterData = new MasterDataModel
{
MasterProperty = viewModel.MasterProperty
};
// Save DetailData
foreach (var detail in viewModel.DetailList)
{
var detailData = new DetailDataModel
{
MasterId = masterData.Id,
DetailProperty1 =