我在使用C#的ASP MVC控制器中有一个非实体的自定义和原始SQL查询。我想将此数据发送到ASP MVC剃刀视图,并以表格格式及其相应的列标题显示它们。如何获取标头(自定义查询可以包含任何数量的表)并以表格格式显示数据?我很感谢您的帮助。
public class QueryScriptController : Controller
{
private EntitiesContext db = new EntitiesContext();
public ActionResult CreateQueryScript(string SqlQueryString )
{
try
{
var ResultList= db.Database.SqlQuery<string>(SqlQueryString).ToList();
return View(ResultList);
}
catch
{
return View();
}
}
}
答案 0 :(得分:0)
在您的控制器中,将数据传递到如下所示的Viewbag,然后将该Viewbag传递到razor视图。
public class QueryScriptController : Controller
{
private EntitiesContext db = new EntitiesContext();
public ActionResult CreateQueryScript(string SqlQueryString )
{
try
{
var ResultList= db.Database.SqlQuery<string>
(SqlQueryString).ToList();
ViewBag.data =ResultList;
return View();
}
catch
{
return View();
}
}
}
在剃须刀页面中,如下所示调用Viewbag并调用从查询中获取的数据对象。
@{
var data = ViewBag.data;
}
using somemodel;
<!DOCTYPE html>
<html style="position: absolute; width: 100%; height: 100%">
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Fira+Sans" rel="stylesheet">
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<title>PaySlip</title>
</head>
<body >
<div class="col-lg-6">
<h5 align="center" style="text-decoration: underline;">Results</h5>
<table className="table-bordered table-striped">
<thead>
<tr>
<th style="width: 60%">Column 1</th>
<th style="width: 30%">Column 2</th>
</tr>
</thead>
<tbody>
@foreach (var item in @data)
{
<tr >
<td style="width: 60%">@item.object1</td>
<td style="width: 30%">@item.object2</td>
</tr>
}
</tbody>
</table>
</div>
</body>
</html>