关于mvc中传入DataTable到视图的应用

MVC 中 如果是多表连接查询出的数据需要重新定义一个ViewModel,觉得很是麻烦,所以可以通过传一个DataTable到视图中可以避免这个问题

但是不知道会有什么不好的地方,有这方面经验的大神有什么看法可以讨论一下。

好了, 直接上代码

public ActionResult Index()
{

var data = from a in db join b in ef.Grade on a.id equals b.id
select new {myname=a.name,gade=b.name};

DataTable dt = LINQToDataTable(data);

return View(dt);
}

//将IEnumerable<T>类型的集合转换为DataTable类型
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{ //定义要返回的DataTable对象
DataTable dtReturn = new DataTable();
// 保存列集合的属性信息数组
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;//安全性检查
//循环遍历集合,使用反射获取类型的属性信息
foreach (T rec in varlist)
{
//使用反射获取T类型的属性信息,返回一个PropertyInfo类型的集合
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
//循环PropertyInfo数组
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;//得到属性的类型
//如果属性为泛型类型
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{ //获取泛型类型的参数
colType = colType.GetGenericArguments()[0];
}
//将类型的属性名称与属性类型作为DataTable的列数据
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
//新建一个用于添加到DataTable中的DataRow对象
DataRow dr = dtReturn.NewRow();
//循环遍历属性集合
foreach (PropertyInfo pi in oProps)
{ //为DataRow中的指定列赋值
dr[pi.Name] = pi.GetValue(rec, null) == null ?
DBNull.Value : pi.GetValue(rec, null);
}
//将具有结果值的DataRow添加到DataTable集合中
dtReturn.Rows.Add(dr);
}
return dtReturn;//返回DataTable对象
}

在视图中和强视图引用的方式一样

@model System.Data.DataTable

之后可以这么调用

<table>
@foreach (System.Data.DataRow dr in Model.Rows)
{
<tr>
<td>
@dr["myname"]
</td>
<td>
@dr["gade"]
</td>
</tr>
}

</table>

原文地址:https://www.cnblogs.com/suppler/p/6541393.html