从Controller返回单个DataTable对我来说很好:
public ActionResult Index()
{
DataTable dtable = new DataTable();
dtable = SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);
ViewBag.Units = dtable;
return View(dtable);
}
我能够从相应的视图中访问它,如下所示:
@using System.Data
@{
ViewBag.Title = "Platypus Report Scheduler";
DataTable ds = ViewBag.Units as DataTable;
var rows = from x in ds.AsEnumerable()
select new
{
unit = x.Field<string>("unit")
};
}
但我需要引用多个数据集;我在Controller中试过这个:
public ActionResult Index()
{
DataTable dtable = new DataTable();
dtable = SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);
ViewBag.Units = dtable;
DataTable rpts = new DataTable();
rpts = SQL.ExecuteSQLReturnDataTable("select ReportName from ReportsLU", CommandType.Text, null);
ViewBag.Reports = rpts;
return View(dtable, rpts);
}
......但它不会编译;我明白了,&#34; 参数1:无法转换为&#39; System.Data.DataTable&#39;到&#39;字符串&#39;&#34;为&#34; dtable &#34;和arg 2的相同错误(&#34; rpts&#34;)。此外,&#34; 最佳重载方法匹配&#39; System.Web.Mvc.Controller.View(string,string)&#39;有一些无效的论点&#34;
解决这个问题的方法是什么?从Controller返回DataTable的通用列表?直接在View中填充后续的DataTables?或... ???
答案 0 :(得分:1)
您需要为View方法提供的是一个模型,它可以是一个包含2个数据表的类:
public class DataModel
{
public DataTable DataTable1 { get; set; }
public DataTable DataTable2 { get; set; }
}
您所犯的错误说明您正在使用的重载(View(string viewName, object model)
)接受视图和模型的名称。
答案 1 :(得分:1)
有两种解决方案。
第一种方法是使用ViewBag
。第二个解决方案(在我个人看来最好)是创建一个新模型,其中包含您需要在视图中使用的所有数据。
首次实施:
public ActionResult Index()
{
DataTable dtable = new DataTable();
dtable = SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);
ViewBag.Units = dtable;
DataTable rpts = new DataTable();
rpts = SQL.ExecuteSQLReturnDataTable("select ReportName from ReportsLU", CommandType.Text, null);
ViewBag.Reports = rpts;
return View();
}
在这种情况下,您不需要将dtable
和rpts
传递给View
方法,因为值在ViewBag
中。
@using System.Data
@{
ViewBag.Title = "Platypus Report Scheduler";
DataTable ds = ViewBag.Units as DataTable;
DataTable ds2 = ViewBag.Reports as DataTable;
// Some other beautiful things
}
第二次实施:
public class YourModel {
public DataTable dt1 { get; set; }
public DataTable dt2 { get; set; }
public DataTable dt3 { get; set; }
// Other properties
}
public ActionResult Index()
{
YourModel model = new YourModel();
DataTable dtable = new DataTable();
dtable = SQL.ExecuteSQLReturnDataTable(SQL.SelectUnitsQuery, CommandType.Text, null);
model.dt1 = dtable;
DataTable rpts = new DataTable();
rpts = SQL.ExecuteSQLReturnDataTable("select ReportName from ReportsLU", CommandType.Text, null);
model.dt2 = rpts;
return View(model);
}
现在在视图中:
@model YourModel
@{
ViewBag.Title = "Platypus Report Scheduler";
// Retrive data in this way:
// Model.dt1
// Model.dt2
// Some other beautiful things
}
在视图中@model YourModel
是基本的!