一.自定义视图模型
model.cs
public class AorBvm
{ public List<Role> GetRole { get; set; } public List<Category> GetCategory { get; set; } public AorBvm(List<Role> roles,List<Category> categories)
{ this.GetRole = roles; this.GetCategory = categories;
}
}控制器方面:
namespace Demo.Controllers
{ public class DemoController : Controller
{
BookShopEntities db = new BookShopEntities(); // GET: Demo
public ActionResult Index()
{
List<Role> r = db.Roles.ToList();
List<Category> ca = db.Categories.ToList(); var obj = new AorBvm(r,ca); return View(obj);
}
}
}view:
@using Demo.Models
@model Demo.Models.AorBvm
@{
ViewBag.Title = "Index";
}<h2>Index</h2>@{
foreach (var item in Model.GetCategory)
{ <p>@item.CName</p>
} <br /> foreach (var item2 in Model.GetRole)
{ <p>@item2.RoleName</p>
}
}
二.通过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中用
原文出处:https://www.cnblogs.com/ZaraNet/p/9570969.html