在我的MedicalProductController
中,我试图让我的Edit
操作能够在一页上编辑多个对象。为此,我计划让我的HTTPPOST
编辑操作方法接收一个,IEnumerable<MedicalProduct>
而不是MedicalProduct
脚手架为我设置的那个。
当我单击保存提交一些更改时,我得到一个ArguementNullException
未处理的在线:_db.Entry(productList).State = EntityState.Modified;
我不明白为什么它是空的。
医疗产品控制器:
public class MedicalProductController : Controller
{
private MvcMedicalStoreDb _db = new MvcMedicalStoreDb();
// some code omitted for brevity
public ActionResult Edit(int id = 0)
{
MedicalProduct product = _db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
var productList = new List<MedicalProduct> { product };
var viewModel = GetMedicalProductViewModelList(productList);
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(IEnumerable<MedicalProduct> productList)
{
if (ModelState.IsValid)
{
_db.Entry(productList).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
//var productList = new List<MedicalProduct> { product };
var viewModel = GetMedicalProductViewModelList(productList);
return View(viewModel);
}
}
编辑.cshtml:
@model IEnumerable<MvcMedicalStore.Models.MedicalProductViewModel>
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>MedicalProduct</legend>
@foreach (var modelItem in Model)
{
@Html.HiddenFor(item => modelItem.ID)
<div class="editor-label">
@Html.LabelFor(item => modelItem.Name)
</div>
<div class="editor-field">
@Html.EditorFor(item => modelItem.Name)
@Html.ValidationMessageFor(item => modelItem.Name)
</div>
<div class="editor-label">
@Html.LabelFor(item => modelItem.Price)
</div>
<div class="editor-field">
@Html.EditorFor(item => modelItem.Price)
@Html.ValidationMessageFor(item => modelItem.Price)
</div>
<div class="editor-label">
@Html.LabelFor(item => modelItem.BrandName)
</div>
<div class="editor-field">
@Html.DropDownListFor(item => modelItem.BrandName, modelItem.BrandSelectListItem)
@Html.ValidationMessageFor(item => modelItem.BrandName)
</div>
}
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}