尝试使用MVC中的表单提交来更新1条以上的记录(将现有数据从数据库导入到视图中,并允许用户进行更改)。
在视图中,我可以返回所有需要准备编辑的现有记录,而不会出现问题:
@model IEnumerable<object>
@{
List<Portal.Models.Primary_Client> PClient = Model.ToList()[0] as List<Portal.Models.Primary_Client>;
List<Portal.Models.Primary_Dependent> PDependant = Model.ToList()[1] as List<Portal.Models.Primary_Dependent>;
List<Portal.Models.Primary_AnnExp> PAnnExp = Model.ToList()[2] as List<Portal.Models.Primary_AnnExp>;
List<Portal.Models.Primary_IncExp> PIncEx = Model.ToList()[3] as List<Portal.Models.Primary_IncExp>;
List<Portal.Models.Primary_InvAssets> PInvAssets = Model.ToList()[4] as List<Portal.Models.Primary_InvAssets>;
List<Portal.Models.Primary_Liabilities> PLiabilities = Model.ToList()[5] as List<Portal.Models.Primary_Liabilities>;
List<Portal.Models.Primary_LifeAssets> PLAssets = Model.ToList()[6] as List<Portal.Models.Primary_LifeAssets>;
ViewBag.Title = "Completed Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("EditPLA/" + newid, "Forms", FormMethod.Post))
{
for (int i = 0; i < PLAssets.Count; i++)
{
<div class="form-group">
@Html.HiddenFor(Model => PLAssets[i].LifAsset_ID)
@Html.HiddenFor(Model => PLAssets[i].PLForm_ID)
@Html.HiddenFor(Model => PLAssets[i].Client_ID_PriFK)
</div>
<div class="container">
<div class="row">
<div class="col-sm">
@Html.Label("Asset Type")
@Html.EditorFor(Model => PLAssets[i].PLAsset_Type, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="col-sm">
@Html.Label("Asset Amount")
@Html.EditorFor(Model => PLAssets[i].PLAmount_Per_Annum, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
</div>
<br />
}
<div class="button" style="text-align:center;">
<input type="submit" class="btn btn-success" value="Save" />
<button class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
}
但是,当我提交表单时,我的模型无法正确填充,因为字段名称没有按预期方式传递并且与我的模型字段名称不匹配。我怀疑这是因为我如何使用循环创建字段。
我的编辑器字段名称如下:
<input class="form-control text-box single-line" id="CS___8__locals1_PLAssets_0__PLAmount_Per_Annum" name="CS$<>8__locals1.PLAssets[0].PLAmount_Per_Annum" type="text" value="3">
当我期望看到更多类似的东西时:
<input class="form-control text-box single-line" id="PLAmount_Per_Annum" name="PLAmount_Per_Annum" type="text" value="3">
我相信这比平时要困难得多,因为我有多个模型通过对象传递给视图,但是我不知道如何用正确的名称创建这些字段。
仅供参考-我的控制器如下所示:
[HttpPost]
public ActionResult EditPLA(List<Primary_LifeAssets> Assets, int id)
{
if (ModelState.IsValid)
{
foreach (var i in Assets)
{
var c = db1.Primary_LifeAssets.Where(a => a.LifAsset_ID.Equals(i.LifAsset_ID)).FirstOrDefault();
if (c != null)
{
c.PLForm_ID = i.PLForm_ID;
c.PLAmount_Per_Annum = i.PLAmount_Per_Annum;
c.PLAsset_Type = i.PLAsset_Type;
}
}
db1.Entry(Assets).State = EntityState.Modified;
db1.SaveChanges();
ViewBag.Message = "Successfully Updated.";
return RedirectToAction("Existing/" + id, "Forms");
}
ViewBag.Message = "Save failed.";
return RedirectToAction("Existing/" + id, "Forms");
}