我希望在后期操作中模型无效时返回同一页面,并附带错误消息和query string
我的代码在这里
public ActionResult Action1(string Key)
{
// do something
}
[HttpPost]
public ActionResult Action1(Model user)
{
if (ModelState.IsValid)
{
// do some stuff here
}
else
// redirect to same page with query string key and also error message
}
请建议我在模型无效时添加的行,以便通过显示错误消息保留在同一页面中。
答案 0 :(得分:3)
public ActionResult Action1(Model user)
{
if (ModelState.IsValid)
{
// all is okay
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
答案 1 :(得分:2)
[HttpPost]
public ActionResult Action1(Model user)
{
if (ModelState.IsValid)
{
// do some stuff here
}
else
{
return this.RedirectToAction ("Action1", new { value1 = "QueryStringValue" });
}
}
那会归还:
/controller/Action1?value1=QueryStringValue
同样根据您的评论。
您可以使用以下方法进行模型,而不是从控制器发送错误以查看模型失败。
[Required]
[DataType(DataType.Text)]
[StringLength(40)]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(1000, MinimumLength = 8)]
public string Password { get; set; }
[Required]
[System.Web.Mvc.Compare("Password")]
[DataType(DataType.Password)]
public string PasswordConfirmation { get; set; }