【发布时间】:2010-11-29 19:37:59
【问题描述】:
我有一个使用实体框架的 ASP.NET MVC 2.0 应用程序。我所有的视图都使用视图模型,其中大多数都很复杂。意思是……要编辑的对象是视图模型的属性,而不是视图模型本身。
我正在使用带有数据注释的部分类,并在控制器的 POST 操作中检查 ModelState.IsValid。
对于一个包含 3 个字段的简单对象,我有一个“新”表单和一个“编辑”表单!
ModelState.IsValid 检查适用于新表单,如果我尝试提交空白表单,则会显示正确的“必填字段”错误。
但是,如果我加载一个 EDIT 表单,并从一些必需的文本框中清除值,然后提交表单,我不会收到验证错误,我只会收到一个异常:
执行处理程序“System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper”的子请求时出错。
所以我的问题是,ModelState.IsValid 是否不适用于 EDIT 表单,因为它可能正在查看加载的视图模型对象中的值,而不是 FormCollection?
// this one does not validate
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int accountStatusKey, AccountStatusEditViewModel model, FormCollection values)
{
if (ModelState.IsValid)
{
db.UpdateAccountStatus(accountStatusKey, values);
return RedirectToAction("States");
}
else
{
return View("Edit", model);
}
}
// this one does validate
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult New(AccountStatusNewViewModel model, FormCollection values)
{
if (ModelState.IsValid)
{
db.AddAccountStatus(values);
return View("States", new AccountStatusStatesViewModel());
}
else
{
return View("New", model);
}
}
// how I arrive AT the edit form
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Edit(int accountStatusKey)
{
return View("Edit", new AccountStatusEditViewModel(accountStatusKey));
}
// and finally, the view model code
public class AccountStatusEditViewModel : ViewModelBase
{
public AccountStatus AccountStatus { get; private set; }
public IEnumerable States { get; private set; }
public List StatusTypes { get; private set; }
public AccountStatusEditViewModel(int accountStatusKey)
{
AccountStatus = db.GetAccountStatusByKey(accountStatusKey);
States = db.GetAllStates();
StatusTypes = new List();
StatusTypes.Add("Primary Status");
StatusTypes.Add("Secondary Status");
StatusTypes.Add("External Status");
}
public AccountStatusEditViewModel()
{
}
}
// this action method does not work at all either - no db updating, no validation
// the page simply redirects to "States" view, which should only happen if the db
// was being updated, right? But nothing is changing in the DB, and the validation
// never happens.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(AccountStatusEditViewModel model)
{
if (ModelState.IsValid)
{
if (TryUpdateModel(model, "AccountStatus"))
{
return RedirectToAction("States");
}
else
{
return View("Edit", model);
}
}
else
{
return View("Edit", model);
}
}
【问题讨论】:
-
你能发布这两种操作方法吗?
-
在您的上一个代码示例中,
public ActionResult Edit(AccountStatusEditViewModel model)出了什么问题?该模型是有效的,并且在重定向到状态视图时会正确更新。当您希望模型包含无效值时,它是否也会这样做? -
无论模型是否有效,我都会被重定向到状态视图,并且数据库中没有任何更新。所以 Model.IsValid 似乎总是正确的,即使表单字段为空(无效)。
标签: entity-framework asp.net-mvc-2 entity-framework-4