在MVC中显示标准DataTable

Jon*_*ien 43 c# asp.net asp.net-mvc

也许这只是完全错误,但是在Webforms的时代,你会返回一个数据集,然后你将它绑定到一个网格.但是现在在MVC中你不应该传递一个数据表,因为你不能序列化它并且技术上将对象传递到它不属于的View中?但是我到底是怎么想在视图上显示数据的呢?!我不能在这里使用LINQ to SQL类,因为这是一个纯粹的内存数据结构.

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

我真的有点不知所措,我已经阅读了"Gu"中的文章,我只能总结一下,我必须传回一个ViewData对象?我疯了吗?

来自Blighty的欢呼声

乔恩

Kur*_*ler 69

这根本不是"错误的",它不是酷人通常用MVC做的事情.顺便说一下,我希望ASP.NET MVC的一些早期演示不会同时尝试在Linq-to-Sql中填充.它非常棒,非常适合MVC,当然,但并不是必需的.MVC无法阻止您使用ADO.NET.例如:

控制器动作:

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
}
Run Code Online (Sandbox Code Playgroud)

查看:( w/Model强类型为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>
Run Code Online (Sandbox Code Playgroud)

现在,我在这里违反了ASP.NET MVC的许多原则和"最佳实践",所以请理解这只是一个简单的演示.创建DataTable的代码应驻留在控制器之外的某个位置,并且View中的代码可能更好地与部分或html帮助程序隔离,以便列举一些您应该执行的操作.

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

我希望这有帮助!


Pro*_*ega 40

这是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>
Run Code Online (Sandbox Code Playgroud)


Tom*_*kel 6

当我尝试上面的方法时,它变成了mvc的彻底灾难.您的控制器使用强类型模型传递模型和视图变得太难以使用.

获取数据集到列表.....我有一个存储库模式,这里是一个从旧学校asmx web服务私有readonly获取数据集的例子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;

    }
Run Code Online (Sandbox Code Playgroud)

然后在控制器中我正在这样做

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);
Run Code Online (Sandbox Code Playgroud)

然后在视图中很容易:

@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>
Run Code Online (Sandbox Code Playgroud)