【发布时间】:2011-06-20 12:03:50
【问题描述】:
我正在重构 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。但是,在我进行更改并单击保存后,通过方法ActionResult Edit(Toy 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
}
【问题讨论】:
-
你能发布你的“编辑”视图吗?
-
...以及
Toy的类主体 - 或者至少是声明ToyId成员的位 -
完成 - 我刚刚重构了 mvcmusicstore。
标签: c# asp.net-mvc asp.net-mvc-3