Creating a MVC ViewModels for my data

前端 未结 5 607
执念已碎
执念已碎 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:17

    Generally, it's a good practice to use a viewmodel. There are several advantages of using them. I think much of the details for viewmodel, you can find on the internet and on stack overflow as well.
    And thus let me give an example or a starting point
    let's say we have a viewmodel;

    public class CategoryViewModel
    {
        [Key]
        public int CategoryId { get; set; }
        [Required(ErrorMessage="* required")]
        [Display(Name="Name")]
        public string CategoryName { get; set; }
        [Display(Name = "Description")]
        public string CategoryDescription { get; set; }
        public ICollection SubCategories { get; set; }
    }
    

    Now, if you wanna use this in your repository project. you can do something like this;

    public List GetAllCategories()
    {
        using (var db =new Entities())
        {
            var categoriesList = db .Categories
                .Select(c => new CategoryViewModel()
                {
                    CategoryId = c.CategoryId,
                    CategoryName = c.Name,
                    CategoryDescription = c.Description
                });
            return categoriesList.ToList();
        };
     }
    

    as, you can see. In case of viewmodel, you need to use the projections (as i have projected my entities to the viewmodel).
    Now, in your controller, you can easily access them and pass it to the view itself;

    ICategoryRepository _catRepo;
        public CategoryController(ICategoryRepository catRepo)
        {
            //note that i have also used the dependancy injection. so i'm skiping that
            _catRepo = catRepo;
        }
        public ActionResult Index()
        {
            //ViewBag.CategoriesList = _catRepo.GetAllCategories();
               or
            return View(_catRepo.GetAllCategories());
        }
    

    And now, your view should be of type CategoryViewModel (the strongly typed)

    @model IEnumerable
    @foreach (var item in Model)
    {
        

    @item.CategoryName

    }

    I hope this gives you a starting point. Let me know, if you need more from me :D

提交回复
热议问题