我在MVC 4中有一个简单的cshtml页面,如下所示:
@model MvcApplication2.ViewModels.UserViewModel
<html>
<head>
<meta name="viewport" content="width=device-width" />
<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>
</head>
<body>
<div>
@using (Html.BeginForm("Add", "User", FormMethod.Post))
{
@Html.ValidationMessageFor(m => m.FirstName)
@Html.TextBoxFor(m => m.Ime)
<br />
@Html.ValidationMessageFor(m => m.LastName)
@Html.TextBoxFor(m => m.LastName)
<br />
<input id="btnSubmit" type="submit" value="Add user" />
}
</div>
</body>
</html>
这是我的UserViewModel类:
public class UserViewModel
{
[Required(ErrorMessage = "This field is required.")]
public string FirstName;
[Required(ErrorMessage = "This field is required.")]
public string LastName;
}
这是控制器中的“添加”操作:
[HttpPost]
public ActionResult Add(User s)
{
if(ModelState.IsValid)
{
Connection.dm.User.Add(s);
Connection.dm.SaveChanges();
}
return RedirectToAction("Index");
}
这里的问题是,如果用户未在2个文本框字段中输入任何内容,我根本不会收到任何错误消息...这可能是什么?
最佳答案
关于使用try .. catch ..块,您可以执行以下操作:
[HttpPost]
public ActionResult Add(User s)
{
if(ModelState.IsValid)
{
try{
Connection.dm.User.Add(s);
Connection.dm.SaveChanges();
}
catch(NullReferenceException)
{
ModelState.AddModelError("Ime", "Please enter something"); // for the first name validation
return View(s);
}
return RedirectToAction("Index");
}
或者您可以使用如下条件逻辑:
[HttpPost]
public ActionResult Add(User s)
{
if(ModelState.IsValid)
{
if(string.IsNullOrWhiteSpace(s.Ime)
{
ModelState.AddModelError("Ime", "Please enter something");
return View(s);
}
else
{
Connection.dm.User.Add(s);
Connection.dm.SaveChanges();
}
}
return RedirectToAction("Index");
}