C# 在 MVC 中显示标准数据表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2243898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:42:37  来源:igfitidea点击:

Displaying standard DataTables in MVC

c#asp.netasp.net-mvc

提问by JonathanTien

Perhaps this is just completely wrong, but back in the days of Webforms you would return a Dataset which you would then bind to a grid. But now in MVC you're not supposed to pass a datatable because you cannot serialize it and it's technically passing objects into the View where it doesn't belong? But how on earth am I meant to display data on a view?! I can't use LINQ to SQL classes here since this is a pure in memory data structure.

也许这完全是错误的,但在 Webforms 时代,您将返回一个数据集,然后您将绑定到网格。但是现在在 MVC 中,您不应该传递数据表,因为您无法对其进行序列化,并且它在技术上将对象传递到它不属于的视图中?但是我到底要如何在视图上显示数据?!我不能在这里使用 LINQ to SQL 类,因为这是纯内存数据结构。

Ideally I'd just like to able to have an object which I can iterate within the view.

理想情况下,我只想拥有一个可以在视图中迭代的对象。

I'm really at a bit of a loss I have read the article from the "Gu"and I can only summarize that I have to pass back a ViewData Object instead?? Am I going nuts here?

我真的有点不知所措我读了“Gu”的文章,我只能总结一下,我必须传回一个ViewData对象??我会在这里发疯吗?

Cheers from Blighty

来自布莱蒂的欢呼

Jon

乔恩

采纳答案by Kurt Schindler

This is not "wrong" at all, it's just not what the cool guys typically do with MVC. As an aside, I wish some of the early demos of ASP.NET MVC didn't try to cram in Linq-to-Sql at the same time. It's pretty awesome and well suited for MVC, sure, but it's not required. There is nothing about MVC that prevents you from using ADO.NET. For example:

这根本不是“错误”,这不是那些很酷的人通常对 MVC 所做的事情。顺便说一句,我希望 ASP.NET MVC 的一些早期演示不要同时尝试在 Linq-to-Sql 中塞满。它非常棒,非常适合 MVC,当然,但这不是必需的。MVC 不会阻止您使用 ADO.NET。例如:

Controller action:

控制器动作:

public ActionResult Index()
{
    ViewData["Message"] = "Welcome to ASP.NET MVC!";

    DataTable dt = new DataTable("MyTable");
    dt.Columns.Add(new DataColumn("Col1", typeof(string)));
    dt.Columns.Add(new DataColumn("Col2", typeof(string)));
    dt.Columns.Add(new DataColumn("Col3", typeof(string)));

    for (int i = 0; i < 3; i++)
    {
        DataRow row = dt.NewRow();
        row["Col1"] = "col 1, row " + i;
        row["Col2"] = "col 2, row " + i;
        row["Col3"] = "col 3, row " + i;
        dt.Rows.Add(row);
    }

    return View(dt); //passing the DataTable as my Model
}

View: (w/ Model strongly typed as System.Data.DataTable)

视图:(带模型强类型为 System.Data.DataTable)

<table border="1">
    <thead>
        <tr>
            <%foreach (System.Data.DataColumn col in Model.Columns) { %>
                <th><%=col.Caption %></th>
            <%} %>
        </tr>
    </thead>
    <tbody>
    <% foreach(System.Data.DataRow row in Model.Rows) { %>
        <tr>
            <% foreach (var cell in row.ItemArray) {%>
                <td><%=cell.ToString() %></td>
            <%} %>
        </tr>
    <%} %>         
    </tbody>
</table>

Now, I'm violating a whole lot of principles and "best-practices" of ASP.NET MVC here, so please understand this is just a simple demonstration. The code creating the DataTable should reside somewhere outside of the controller, and the code in the View might be better isolated to a partial, or html helper, to name a few ways you shoulddo things.

现在,我在这里违反了 ASP.NET MVC 的很多原则和“最佳实践”,所以请理解这只是一个简单的演示。创建 DataTable 的代码应该驻留在控制器之外的某个地方,而 View 中的代码可能更好地与部分或 html 帮助程序隔离,以列举一些您应该做的事情。

You absolutely are supposed to pass objects to the View, if the view is supposed to present them. (Separation of concerns dictates the view shouldn't be responsible for creatingthem.) In this case I passed the DataTable as the actual view Model, but you could just as well have put it in ViewData collection. Alternatively you might make a specific IndexViewModel class that contains the DataTable and other objects, such as the welcome message.

如果视图应该显示它们,您绝对应该将对象传递给 View。(关注点分离规定视图不应该负责创建它们。)在这种情况下,我将 DataTable 作为实际视图模型传递,但您也可以将它放在 ViewData 集合中。或者,您可以创建一个包含 DataTable 和其他对象(例如欢迎消息)的特定 IndexViewModel 类。

I hope this helps!

我希望这有帮助!

回答by Tom Stickel

While I tried the approach above, it becomes a complete disaster with mvc. Your controller passing a model and your view using a strongly typed model become too difficult to work with.

虽然我尝试了上面的方法,但它对 mvc 来说完全是一场灾难。您传递模型的控制器和使用强类型模型的视图变得难以使用。

Get your Dataset into a List ..... I have a repository pattern and here is an example of getting a dataset from an old school asmx web service private readonly CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient;

将您的数据集放入列表中..... 我有一个存储库模式,这是从旧式 asmx Web 服务私有只读 CISOnlineSRVDEV.ServiceSoapClient _ServiceSoapClient; 获取数据集的示例。

    public Get_Client_Repository()
        : this(new CISOnlineSRVDEV.ServiceSoapClient())
    {

    }
    public Get_Client_Repository(CISOnlineSRVDEV.ServiceSoapClient serviceSoapClient)
    {
        _ServiceSoapClient = serviceSoapClient;
    }


    public IEnumerable<IClient> GetClient(IClient client)
    {
        // ****  Calling teh web service with passing in the clientId and returning a dataset
        DataSet dataSet = _ServiceSoapClient.get_clients(client.RbhaId,
                                                        client.ClientId,
                                                        client.AhcccsId,
                                                        client.LastName,
                                                        client.FirstName,
                                                        "");//client.BirthDate.ToString());  //TODO: NEED TO FIX

        // USE LINQ to go through the dataset to make it easily available for the Model to display on the View page
        List<IClient> clients = (from c in dataSet.Tables[0].AsEnumerable()
                                 select new Client()
                                 {
                                     RbhaId = c[5].ToString(),
                                     ClientId = c[2].ToString(),
                                     AhcccsId = c[6].ToString(),
                                     LastName = c[0].ToString(), // Add another field called   Sex M/F  c[4]
                                     FirstName = c[1].ToString(),
                                     BirthDate = c[3].ToDateTime()  //extension helper  ToDateTime()
                                 }).ToList<IClient>();

        return clients;

    }

Then in the Controller I'm doing this

然后在控制器中我这样做

IClient client = (IClient)TempData["Client"];

// Instantiate and instance of the repository 
var repository = new Get_Client_Repository();
// Set a model object to return the dynamic list from repository method call passing in the parameter data
var model = repository.GetClient(client);

// Call the View up passing in the data from the list
return View(model);

Then in the View it is easy :

然后在视图中很容易:

@model IEnumerable<CISOnlineMVC.DAL.IClient>

@{
    ViewBag.Title = "CLIENT ALL INFORMATION";
}

<h2>CLIENT ALL INFORMATION</h2>

<table>
    <tr>
        <th></th>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Client ID</th>
        <th>DOB</th>
        <th>Gender</th>
        <th>RBHA ID</th>
        <th>AHCCCS ID</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Select", "ClientDetails", "Cis", new { id = item.ClientId }, null) |
        </td>
        <td>
            @item.LastName
        </td>
        <td>
            @item.FirstName
        </td>
         <td>
            @item.ClientId
        </td>
         <td>
            @item.BirthDate
        </td>
         <td>
            Gender @* ADD in*@
        </td>
         <td>
            @item.RbhaId
        </td>
         <td>
            @item.AhcccsId
        </td>
    </tr>
}

</table>

回答by ProVega

Here is the answer in Razor syntax

这是 Razor 语法的答案

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>