问题描述
来自WebForms,我仍然是ASP.net MVC的新手。
我需要显示一个HTML表格,其中列在设计时未知。我有以下两个MS SQL表,它们表示将在运行时显示哪些列。
Coming from WebForms, I'm still brand new to ASP.net MVC.
I have a need to display a HTML table where the columns are unknown at design-time. I have the following two MS SQL tables which denote which columns will be displayed at runtime.
CREATE TABLE ActualData (
Col1 int,
Col2 int,
Col3 int,
Col4 int
)
INSERT INTO ActualData (Col1, Col2, Col3, Col4) VALUES (1, 2, 3, 4)
CREATE TABLE ColumnsToShow (
UserID int,
ColName varchar(10)
)
INSERT INTO ColumnsToShow(UserID, ColName) VALUES (1, 'Col1')
INSERT INTO ColumnsToShow(UserID, ColName) VALUES (1, 'Col2')
INSERT INTO ColumnsToShow(UserID, ColName) VALUES (2, 'Col3')
INSERT INTO ColumnsToShow(UserID, ColName) VALUES (2, 'Col4')
因此视图显示只有ActualData.Col1和ActualData.Col2到用户1,并且
ActualData.Col3和ActualData.Col4到用户2.
我知道在webforms中我可能会做这样的事情,在将数据表绑定到GridView控件之前删除匹配的列。
So that the view shows only ActualData.Col1 and ActualData.Col2 to user 1, and
ActualData.Col3 and ActualData.Col4 to user 2.
I know in webforms I would probably have done something like this, to remove matching columns before binding the datatable to a GridView control.
DataTable dtData = GetActualData(); // db call
List<string> colsToRemove = GetColumnsToRemove(); // db call returning only the fields to remove
// remove columns not neccessary for the current user
foreach (string colName in colsToRemove)
foreach (DataColumn dc in dtData.Columns)
if (dc.ColumnName == colName)
dtData.Columns.Remove(colName);
// bind the datatable to a GridView
gridview.AutoGenerateColumns = true;
gridview.DataSource = dtData;
gridview.DataBind();
MVC的新手,我真的不知道从哪里开始。所以任何建议都会受到赞赏。
我尝试过:
还没有尝试任何东西,因为我正在寻找从哪里开始。
New to MVC, I really don't even know where to start. So any advice would be appreciated.
What I have tried:
Haven't tried anything yet, as I am looking for idea where to start.
推荐答案
var columns = new List<WebGridColumn>(dtData.Columns.Count);
foreach (DataColumn column in dtData.Columns)
{
columns.Add(new WebGridColumn
{
ColumnName = column.ColumnName,
Header = column.Caption,
});
}
ViewBag.Columns = columns;
return View(dtData);
然后,在您看来:
Then, in your view:
@model DataTable
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml(columns: ViewBag.Columns)
或者,你可以将 DataTable
转换为动态对象列表,如 []。
Alternatively, you could convert your DataTable
to a list of dynamic objects, as described in this StackOverflow answer[^].
var model = new List<dynamic>(dtData.Rows.Count);
foreach (DataRow row in dtData.Rows)
{
var obj = (IDictionary<string, object>)new ExpandoObject();
foreach (DataColumn col in dtData.Columns)
{
obj.Add(col.ColumnName, row[col]);
}
model.Add(obj);
}
return View(model);
然后,在您看来:
Then, in your view:
@model IList<dynamic>
@{
var grid = new WebGrid(Model);
}
@grid.GetHtml()
这篇关于Asp.net MVC如何显示动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!