一、控制器向视图传递参数的两种形式:使用到的技术有EF,linq表达式,StringBuilder,相关技术都可以在我的博客园中找到详细的技术介绍。
1. 第一种是通过字符通过foreach循环拼接将table标签里的td放在一个StringBuilder中,然后通过ViewData传递给视图文件。以下就是相关代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using System.Text;
namespace MvcApplication1.Controllers
{
public class UserInfoController : Controller
{
// GET: /UserInfo/
public ActionResult Index()
{
wangjin2Entities1 db = new wangjin2Entities1();
var userinfolist = db.Userinfo.Where<Userinfo>
(u => true);
StringBuilder sb = new StringBuilder();
foreach (var userinfo in userinfolist)
{
sb.AppendFormat("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td></tr>", userinfo.Id, userinfo.username, userinfo.password, userinfo.Emil, userinfo.CreateDate.ToShortDateString());
}
//控制器向视图传数据
ViewData["userinfolist"]=sb.ToString();
return View();
//方法
}
}
}
1.1 视图代码
<body>
<div>
<table>
<tr><th>ID</th><th>用户名</th><th>密码</th><th>邮箱</th><th>创建日期</th></tr>
<%=ViewData["userinfolist"] %>
</table>
</div>
</body>
2. 第二种是直接将EF查到的数据传递给前端页面,但是前端接收的时候就需要对数据进行处理。代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using System.Text;
namespace MvcApplication1.Controllers
{
public class UserInfoController : Controller
{
// GET: /UserInfo/
public ActionResult Index()
{
wangjin2Entities1 db = new wangjin2Entities1();
var userinfolist = db.Userinfo.Where<Userinfo>
(u => true);
ViewData["userinfolist"] =userinfolist;
return View();
}
}
}
2.1 前端代码中需要用到导入命名空间,并且将数据强转成IQueryable。具体代码如下:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Import Namespace="MvcApplication1.Models" %>
<!DOCTYPE html> <html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
<tr><th>ID</th><th>用户名</th><th>密码</th><th>邮箱</th><th>创建日期</th></tr>
<%-- <%=ViewData["userinfolist"] %>--%>
<%foreach( var userinfo in (IQueryable<Userinfo>)ViewData["userinfolist"]) {%>
<tr>
<td><%=userinfo.Id %></td>
<td><%=userinfo.username %></td>
<td><%=userinfo.password %></td>
<td><%=userinfo.Emil %></td>
<td><%=userinfo.CreateDate.ToShortDateString() %></td>
</tr>
<%} %>
</table>
</div>
</body>
</html>