Asp.net mvc 3 MVC3中TryUpdateModel的问题
我对MVC3中的TryUpdate模型有问题 启动编辑(post)时,我有以下代码:Asp.net mvc 3 MVC3中TryUpdateModel的问题,asp.net-mvc-3,Asp.net Mvc 3,我对MVC3中的TryUpdate模型有问题 启动编辑(post)时,我有以下代码: public ActionResult Edit(int id, FormCollection collection) { var review = FoodDB.FindByID(id); if (TryUpdateModel(review)) return RedirectToAction("Index"); retur
public ActionResult Edit(int id, FormCollection collection)
{
var review = FoodDB.FindByID(id);
if (TryUpdateModel(review))
return RedirectToAction("Index");
return View(review);
}
视图由VS直接构建(因此我不会更改)
如果我跟踪代码,我会在FormCollection中看到新的值,但是在执行TryUpdateModel之后,它返回true,不会抛出任何错误,但是review对象不会更新
我会做错什么
编辑
我提出了更多细节:
首先,db不是真正的db,只是一个带有一个静态genric列表的“模拟”类
List<Review> Review;
视图是强类型的,由VS从控制器的编辑方法生成。字段定义如下:
public class Review
{
public string Message { get; set; }
public DateTime Created { get; set; }
public int ID { get; set; }
public int Rating { get; set; }
}
<div class="editor-label">
@Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Message)
@Html.ValidationMessageFor(model => model.Message)
</div>
@Html.HiddenFor(model => model.ID)
<div class="editor-label">
@Html.LabelFor(model => model.Rating)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rating)
@Html.ValidationMessageFor(model => model.Rating)
</div>
因此,据我所知,TryUpdateMethod应该在集合中找到适当的字段进行更新
那么,有什么不对呢
感谢大家基于您发布的代码,审阅对象不会更新,因为FormCollection中的新值尚未绑定到您的模型。您没有使用
DefaultModelBinder
如果您的视图是强类型的(并且假设类型类名为Food
),请按如下方式更改您的方法签名和方法:
public ActionResult Edit(Food food)
{
if (ModelState.IsValid)
{
FoodDB.Update(food);
return RedirectToAction("Index");
}
return View(food);
}
DefaultModelBinder将从表单中获取值并将其绑定到您的模型。您需要提供更多信息。查看对象是什么样子的?它包含哪些属性和类型?景色怎么样?它是由VS自动生成的这一事实并不意味着它会工作。您能否确认
FoodDB.FindByID(id)
返回的内容以及类型?另外,如果您使用的是强类型视图,那么就不需要FormCollection集合
如何知道这些值没有更新?您是否设置了断点并查看对象,还是正在查看数据库?因为您从未调用SaveChanges()来实际保存更新的对象。
public ActionResult Edit(Food food)
{
if (ModelState.IsValid)
{
FoodDB.Update(food);
return RedirectToAction("Index");
}
return View(food);
}