How are you populating/validating your ViewModels?

后端 未结 4 365
闹比i
闹比i 2021-01-30 03:40

I\'m curious of all of the various ways people are building their ViewModels and why they choose that method.

I can think of several ways here:

-1. Injected repo

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 04:10

    Our method is to inject the repository in to the controller and map it to the ViewModel using Automapper http://automapper.org/. Our ViewModels contain data annotation attributes to allow the validation to occur on the client.

    We call methods on the repository which return Domain objects (Entity Framework). The domain objects are mapped to the ViewModel. We tend to use the same ViewModel for edits and adds so the data annotations are needed once. In its simplest form it looks like the following code:

        public ActionResult List(int custId, int projId)
        {
            var users = _userRepository.GetByCustomerId(custId);
            var userList = Mapper.Map, IEnumerable>(users);
            return View(userList);
        }
    

提交回复
热议问题