MVC的传递数据的方法

1、使用ViewBag

         #region 0.2 Action方法 + ActionResult Index2()
/// <summary>
/// Action方法
/// </summary>
/// <returns></returns>
public ActionResult Index2()
{
System.Text.StringBuilder sbhtml = new System.Text.StringBuilder();
List<Models.dog> list = InitData();
list.ForEach(d =>
{
sbhtml.AppendLine("<div>" + d.ToString() + "</div>");
}); ViewBag.HtmlStr = sbhtml.ToString(); return View();
}
#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

         #region 0.3 查询文章列表 + ActionResult Index3()
/// <summary>
/// 查询 文章 列表
/// </summary>
/// <returns></returns>
OumindBlogEntities db = new OumindBlogEntities(); public ActionResult Index3()
{
List<Models.BlogArticle> list = (from d in db.BlogArticles where d.AIsDel == false select d).ToList(); ViewData["DataList"] = list;
return View();
}
#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()

         #region 0.5 显示要修改数据(根据Id) +  ActionResult Modify(int id)
[HttpGet]
/// <summary>
/// 显示要修改的数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public ActionResult Modify(int id)
{
//1.根据id查询出要修改的对象
BlogArticle art = (from a in db.BlogArticles where a.AId == id select a).FirstOrDefault();
//2.生产文章分类下来框
IEnumerable<SelectListItem> listItem = (from c in db.BlogArticleCates
where c.IsDel == false select c).ToList()
.Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Name });
//3.将生成的文章分类 下拉框集合 设置给ViewBag
ViewBag.CateList = listItem;
//4.加载视图,使用View构造函数,将数据传给视图上Model属性
return View(art);
}
#endregion
上一篇:Spring学习之AOP


下一篇:Eclipse的Tomcat热部署,免重启的方法