我有一个使用实体框架的ASP.NET MVC 2.0应用程序。我所有的观点都使用视图模型,其中大部分都是复杂的。含义...要编辑的对象是视图模型的属性,而不是视图模型本身。ModelState.IsValid在“新”表单上工作,但不在“编辑”表单上工作
我在数据注释中使用了部分类,并在控制器中的POST动作中检查了ModelState.IsValid。
我有一个“新”形式和一个“编辑”窗体为3个字段的简单对象!
ModelState.IsValid检查适用于新窗体,并显示正确的“必填字段”错误,如果我尝试提交空白窗体。
但如果我加载一个编辑表单,并从需要一些文本框清除值,并提交表单,我没有得到验证错误,我只是得到一个异常:
错误执行子请求处理程序'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);
}
}
你可以发布两种操作方法吗? – Mariusz 2010-11-29 19:49:25
已发布代码 – Blackcoil 2010-11-29 20:04:21
在您最后的代码示例中,“public ActionResult Edit(AccountStatusEditViewModel model)”出了什么问题?该模型是有效的,并且在重定向到状态视图时正确更新。当你期望模型包含无效值时,它是否也这样做? – Michel 2010-11-30 07:48:50