Creating a MVC ViewModels for my data

前端 未结 5 617
执念已碎
执念已碎 2020-12-22 09:46

Im still new to this MVC thing so is my understanding correct in terms of MVC View Models. They are essentially models that will interact directly with the view, where as a

5条回答
  •  误落风尘
    2020-12-22 10:13

    You seem to have the right idea. Generally you will want to pass a view model to your view, especially in a case like this where you need data from two or more entity models. Far too often on this site we see people sending an entity model and then some other data by way of a ViewBag or ViewData, and inevitably, the solution to their problem is to use a view model.

    The view model may look like this:

    public class ViewModel
    {
        public int UserId { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public DateTime CreatedDate { get; set; }
        public String Description { get; set; }
    }
    

    This flattened version is useful for adding data annotations at the view model level instead of the entity model level. Handy when you may want to require a field in one view, but not in another.

    Or like this

    public class ViewModel
    {
       public UserModel UserModel { get; set; }
       public String Description { get; set; }
    }
    

    You could do this

    public class ViewModel
    {
       public UserModel UserModel { get; set; }
       public ArticleModel ArticleModel { get; set; }
    }
    

    But then you would be sending superfluous data to the view which can often cause problems for folks as their app grows in scope

提交回复
热议问题