What role does MVVM play in ASP.NET MVC 4 web applications?

前端 未结 5 1012
心在旅途
心在旅途 2021-02-14 03:17

While I\'m reading the book \"ASP.NET MVC 4\" I\'m wondering about MVVM. I started googling and cannot find any books about developing web applications using MVVM, so I must be

5条回答
  •  粉色の甜心
    2021-02-14 03:54

    MVVM is really sort of a subpattern. There's not really any "MVVM" web app frameworks out there. They're all MVC and you pretty much just incorporate a view model if you want one.

    With ASP.NET MVC, in particular, you just create a class, generally with a name in the form of [Model Name]ViewModel or [Model Name]VM. That class will have only the properties from your model that you'll need to work with and anything extra that doesn't make sense to put on your actual database-backed model, like SelectLists, etc.

    In your action, you just pass an instance of this view model to your view instead of your model:

    return View(viewModelInstance);
    

    And, of course, make sure your view accepts that:

    @model Namespace.To.MyViewModel
    

    The only slightly complicated part is wiring the view model to the model (i.e., getting data to/from the view model/model. You can do this manually by explicitly mapping the properties, or you can use something like AutoMapper.

提交回复
热议问题