Validation on ViewModels in ASP.NET MVC

后端 未结 2 642
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 06:23

Most of the tips on how to implement validation in ASP.NET MVC seem to center around the Model (either building service layers between model and controller or decorating propert

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 06:53

    The NerdDinner tutorials show the validation as occurring in your partial classes of the model (i.e. Linq to SQL or Entity Framework). But since you're using View Models, you can put the validation logic there.

    The Validation Logic doesn't go in the controller. Rather, it is hooked from the controller with a checking property, i.e. ModelState.IsValid

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Dinner dinner) {
    
        if (ModelState.IsValid) {
    
            try {
                dinner.HostedBy = "SomeUser";
    
                dinnerRepository.Add(dinner);
                dinnerRepository.Save();
    
                return RedirectToAction("Details", new { id=dinner.DinnerID });
            }
            catch {
                ModelState.AddModelErrors(dinner.GetRuleViolations());
            }
        }
    
        return View(new DinnerFormViewModel(dinner));
    }
    

    Full details are here:

    Building the Model
    http://nerddinnerbook.s3.amazonaws.com/Part3.htm

    and here:

    ViewData and ViewModel
    http://nerddinnerbook.s3.amazonaws.com/Part6.htm

提交回复
热议问题