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;
}
}
}
編集:dataannotationsを使用して期待どおりに機能および検証する最終的なコード。マーレに感謝します。
[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);
}