如何从控制器返回多个数据集
本文关键字:数据集 返回 控制器 | 更新日期: 2024-10-21 21:52:32
从控制器返回单个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")
};
}
但我需要引用多个数据集;我在控制器中尝试过:
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);
}
但它不会编译;对于"dtable",我得到了"参数1:无法从"System.Data.DataTable"转换为"string",而对于参数2("rpts"),也出现了相同的错误。此外,"与System.Web.Mvc.Controller.View(string,string)'匹配的最佳重载方法有一些无效参数"
解决这个问题的方法是什么?是否从控制器返回DataTable的通用列表?是否直接在视图中填充后续数据表?或
有两种解决方案。
第一种是像您已经做的那样使用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
是基础!
您需要为View方法提供一个模型,该模型可以是包含两个数据表的类:
public class DataModel
{
public DataTable DataTable1 { get; set; }
public DataTable DataTable2 { get; set; }
}
您遇到的错误说明您正在使用的重载(View(string viewName, object model)
)接受视图和模型的名称。