我正在重构MvcMusicStore代码,我正在更新StoreManagerController。我已将编辑操作更改为以下内容:
//
// GET: /StoreManager/Edit/5
public ActionResult Edit(int id)
{
Toy toy = dbStore.Toys.Find(id);
ViewBag.CategoryId = new SelectList(dbStore.Categories, "CategoryId", "Name", toy.CategoryId);
ViewBag.BrandId = new SelectList(dbStore.Brands, "BrandId", "Name", toy.BrandId);
return View(toy);
}
//
// POST: /StoreManager/Edit/5
[HttpPost]
public ActionResult Edit(Toy toy)
{
if (ModelState.IsValid)
{
dbStore.Entry(toy).State = EntityState.Modified;
dbStore.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(dbStore.Categories, "CategoryId", "Name", toy.CategoryId);
ViewBag.BrandId = new SelectList(dbStore.Brands, "BrandId", "Name", toy.BrandId);
return View(toy);
}
在测试时,当我点击Edit
操作时,视图显示正常,并在Edit(int id)
方法中设置断点显示ToyId
为1.但是,在我制作之后更改并单击“保存”,通过方法Toy
传递的ActionResult Edit(Toy toy)
对象的ToyId
不正确等于0.
这次修改发生在哪里,或者是否有一个toy
的副本从视图中传回并且没有正确地复制到ToyId上?
更新:添加了编辑视图的帖子
@model Store.Models.Toy
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Toy</legend>
@Html.HiddenFor(model => model.ToyId)
<div class="editor-label">
@Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
@Html.DropDownList("CategoryId", String.Empty)
@Html.ValidationMessageFor(model => model.CategoryId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.BrandId, "Brand")
</div>
<div class="editor-field">
@Html.DropDownList("BrandId", String.Empty)
@Html.ValidationMessageFor(model => model.BrandId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.PictureUrl)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PictureUrl)
@Html.ValidationMessageFor(model => model.PictureUrl)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
玩具类
[Bind(Exclude = "ToyId")]
public class Toy
{
[ScaffoldColumn(false)]
public int ToyId { get; set; }
// ... other stuff here
}
答案 0 :(得分:1)
这是因为
[Bind(Exclude = "ToyId")]
因此,在绑定操作中字面意义地忽略了ToyID属性,并且未使用隐藏值。
您可以简单地从类中删除它,以便从POST操作中正确绑定ToyId
;或者,您可以通过将id
路由值复制到Toy
的{{1}}属性(或添加名为ToyId
的方法参数)来手动将其绑定到控制器方法中它会自动绑定。)
然而,允许绑定ID属性等存在一些潜在问题,而另一个SO提供了一个窗口:ASP.NET MVC - Alternative for [Bind(Exclude = "Id")]