ASP.NET MVC one view bind many model

一.自定义视图模型

model.cs

 public class AorBvm
    {
        public List GetRole { get; set; }
        public List GetCategory { get; set; }
        public AorBvm(List roles,List categories)
        {
            this.GetRole = roles;
            this.GetCategory = categories;
        }
    }

控制器方面:

namespace Demo.Controllers
{
    public class DemoController : Controller
    {
        BookShopEntities db = new BookShopEntities();
        // GET: Demo
        public ActionResult Index()
        {
            List r = db.Roles.ToList();
            List ca = db.Categories.ToList();
            var obj = new AorBvm(r,ca);
            return View(obj);
        }
    }
}

view:

@using Demo.Models
@model Demo.Models.AorBvm
@{
    ViewBag.Title = "Index";
}

Index

@{ foreach (var item in Model.GetCategory) {

@item.CName

}
foreach (var item2 in Model.GetRole) {

@item2.RoleName

} }

ASP.NET MVC one view bind many model_第1张图片

 

 

二.通过viewbag或者viewmodel

ViewData与ViewBag的区别

1、ViewData是字典类型,赋值方式用字典方式,通过key值读取对应的value,ViewData[“myName”]

2、ViewBag是动态类型,使用时直接添加属性赋值即可ViewBag.myName

3、ViewBag和ViewData只在当前Action中有效,等同于View

4、ViewData和ViewBag中的值可以互相访问,因为ViewBag的实现中包含了ViewData

直接写,直接在view中用

你可能感兴趣的:(ASP.NET MVC one view bind many model)