1、使用ViewBag
1 #region 0.2 Action方法 + ActionResult Index2() 2 /// <summary> 3 /// Action方法 4 /// </summary> 5 /// <returns></returns> 6 public ActionResult Index2() 7 { 8 System.Text.StringBuilder sbhtml = new System.Text.StringBuilder(); 9 List<Models.dog> list = InitData(); 10 list.ForEach(d => 11 { 12 sbhtml.AppendLine("<div>" + d.ToString() + "</div>"); 13 }); 14 15 ViewBag.HtmlStr = sbhtml.ToString(); 16 17 return View(); 18 } 19 #endregion
Index2.cshtml
@{Layout = null; }<!DOCTYPE html><html> <head><meta name="viewport" content="width=device-width" /><title>Index</title> </head> <body>@Html.Raw(ViewBag.HtmlStr)</body> </html>
2、使用ViewData
1 #region 0.3 查询文章列表 + ActionResult Index3() 2 /// <summary> 3 /// 查询 文章 列表 4 /// </summary> 5 /// <returns></returns> 6 OumindBlogEntities db = new OumindBlogEntities(); 7 8 public ActionResult Index3() 9 { 10 List<Models.BlogArticle> list = (from d in db.BlogArticles where d.AIsDel == false select d).ToList(); 11 12 ViewData["DataList"] = list; 13 return View(); 14 } 15 #endregion
Index3.cshtml
@using MvcLewisTest.Models; @{Layout = null; }<!DOCTYPE html><html> <head><meta name="viewport" content="width=device-width" /><title>Index</title><style type="text/css">#tbList{border:1px solid #0094ff;border-collapse:collapse;margin:10px auto;width:800px;}#tbList th,td{border:1px solid #0094ff;padding:10px;}</style><script type="text/javascript">function del(Aid) {if (confirm("确定要删除吗?"))window.location = "/Home/Del/" + Aid; }</script> </head> <body><table id="tbList"><tr> <th>id</th><th>标题</th><th>分类</th><th>状态</th><th>时间</th><th>操作</th></tr>@foreach (BlogArticle a in ViewData["DataList"] as List<BlogArticle>) {<tr> <td>@a.AId</td><td>@a.ATitle</td><td>@a.BlogArticleCate.Name</td><td>@a.Enumeration.e_cname</td><td>@a.AAddtime</td><td><a href="javascript:del(@a.AId)">删</a><a href="/Home/Modify/@a.AId">改</a></td></tr>}</table> </body> </html>
3、使用Control器的 return View()
1 #region 0.5 显示要修改数据(根据Id) + ActionResult Modify(int id) 2 [HttpGet] 3 /// <summary> 4 /// 显示要修改的数据 5 /// </summary> 6 /// <param name="id"></param> 7 /// <returns></returns> 8 public ActionResult Modify(int id) 9 { 10 //1.根据id查询出要修改的对象 11 BlogArticle art = (from a in db.BlogArticles where a.AId == id select a).FirstOrDefault(); 12 //2.生产文章分类下来框 13 IEnumerable<SelectListItem> listItem = (from c in db.BlogArticleCates 14 where c.IsDel == false select c).ToList() 15 .Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Name }); 16 //3.将生成的文章分类 下拉框集合 设置给ViewBag 17 ViewBag.CateList = listItem; 18 //4.加载视图,使用View构造函数,将数据传给视图上Model属性 19 return View(art); 20 } 21 #endregion