我有一个 Asp.NET MVC 应用程序,我在其中使用数据注释向某些字段添加验证:
[Required]
[DisplayName("Course Name")]
string Name { get; set; }
然而,这似乎并没有像我预期的那样工作。基本上,如果页面包含我手动检查并抛出新 RuleViolation() 的任何其他错误,则所需的违规将显示在验证摘要中。如果所需的违规是唯一的错误,则不会显示。
我的控制器中有以下代码:
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
ModelState.AddRuleViolations(courseViewModel.Course.GetRuleViolations());
return View(courseViewModel);
}
但鉴于规定的违规行为不是投掷,我从不进入这里。
我是否需要做一些我不知道的事情来捕获 DataAnnotation 违规引发的错误?
谢谢你的帮助
编辑:
这是控制器动作:
[HttpPost]
[ValidateInput(true)]
public ActionResult Edit(int id, CourseViewModel courseViewModel)
{
var oldCourse = _eCaddyRepository.GetCourse(id);
if (courseViewModel.Course == null)
{
return View("NotFound", string.Format("Course {0} Not Found", id));
}
try
{
courseViewModel.Update(oldCourse);
_eCaddyRepository.SubmitChanges();
return RedirectToAction("Index", "Course");
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
ModelState.AddRuleViolations(courseViewModel.Course.GetRuleViolations());
return View(courseViewModel);
}
}
更新在哪里:
public class CourseViewModel : BaseViewModel
{
public Course Course { get; set; }
public void Update(Course oldCourse)
{
oldCourse.Name = this.Course.Name != null ? this.Course.Name.Trim() : string.Empty;
oldCourse.Postcode = this.Course.Postcode != null ? this.Course.Postcode.Trim() : string.Empty;
for (var i = 0; i < 18; i++)
{
oldCourse.Holes[i].Par = this.Course.Holes[i].Par;
oldCourse.Holes[i].StrokeIndex = this.Course.Holes[i].StrokeIndex;
}
}
}
编辑:使用数据注释按预期工作和验证的最终代码。感谢母马。
[HttpPost]
[ValidateInput(true)]
public ActionResult Edit(int id, CourseViewModel courseViewModel)
{
var oldCourse = _eCaddyRepository.GetCourse(id);
if (courseViewModel.Course == null)
{
return View("NotFound", string.Format("Course {0} Not Found", id));
}
if (ModelState.IsValid)
{
try
{
courseViewModel.Update(oldCourse);
_eCaddyRepository.SubmitChanges();
return RedirectToAction("Index", "Course");
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
// Return Model with errors
ModelState.AddRuleViolations(courseViewModel.Course.GetRuleViolations());
return View(courseViewModel);
}