Designing an MVC repository using ViewModels

前端 未结 3 945
一个人的身影
一个人的身影 2021-02-04 17:25

I want to create a repository class to separate out my data logic from my controllers. I am using a ViewModel to represent some data that will be filled with data from differen

3条回答
  •  渐次进展
    2021-02-04 17:42

    I think you may have a misunderstanding of the view model and it's purpose. You don't need to create a view model for every entity in your database, as it seems you want to do; you just create a view model for each view you want to render. Hence the term "view model"--it organizes the data in the form of a model that your view can be strongly typed to.

    You wouldn't, for example, want to create a separate view model for every entity returned by a GetAll(). In a simple scenario of displaying a gridview of all records you would probably just need a single viewmodel with one property:

        public class MyViewModel
        {     
           public List AllRecords {get;set;}
        }
    

    You would populate this view model in the controller

    public ActionResult SomeAction()
    {
       var viewmodel = new MyViewModel{AllRecords = GetAll()};
       return View(viewModel);
    }
    

    Have a look at this blog post by Rachael Appel for a really concise discussion.

提交回复
热议问题