ViewBag属性: public dynamic ViewBag { get { if (_dynamicViewData == null) { _dynamicViewData = new DynamicViewDataDictionary(() => ViewData); } return _dynamicViewData; } } ViewData属性: public ViewDataDictionary ViewData { get { if (_viewData == null) { SetViewData(new ViewDataDictionary()); } return _viewData; } set { SetViewData(value); } }
具体实例如下: 在Controller中使用ViewData: public ActionResult Index(){ ViewData对应的index.cshtml页面: <p>
在Controller中使用ViewBug: public ActionResult Index(){ List<string> colors = new List<string>(); colors.Add("red"); colors.Add("green"); colors.Add("blue"); ViewBag.ListColors = colors; //colors is List ViewBag.DateNow = DateTime.Now; ViewBag.Name = "Hajan"; ViewBag.Age = 25; return View(); } ViewBug对应的index.cshtml页面: <p> My name is <b><%: ViewBag.Name %></b>, <b><%: ViewBag.Age %></b> years old. <br /> I like the following colors: </p> <ul id="colors">
|
|