如何将c#变量绑定到HTML

时间:2016-10-28 08:36:57

标签: c# jquery asp.net-mvc

我已经从控制器中的SQL查询创建了一个DataTable。

如何将“#example”与“类别”“连接”?

  

EDIT1:建议使用jQuery.DataTables

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Employee Index Page</title>
</head>
<body>
    <div>
    <h1>Employee Index Page</h1>
        <table id="example">

</div>
</body>
</html>

@{ var categories = (System.Data.DataTable)ViewData["MyData"]; }

<script>
    $(document).ready(function () {
        $('#example').DataTable();
    });
</script>
  

ORIGINAL

I want to assign this to a gridview. The Code from the View is below but GridView1 needs to be defined somehow.

In the c# categories has the right contents, but GridView1 get the error "does not exist in the current context".

How and where do I fix that?

    @{
        Layout = null;
    }

    <!DOCTYPE html>

    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Employee Index Page</title>
    </head>
    <body>
        <div>
        <h1>Employee Index Page</h1>
            <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
                          runat="server" DataSource='<%# GetData() %>' AutoGenerateColumns="true">
            </asp:GridView>
            @{ 
                var categories = (System.Data.DataTable)ViewData["MyData"];
                GridView1.DataSource = categories;
                GridView1.DataBind();
            }
        </div>
    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

首先,我建议您不要在一个视图中添加任何内容,创建网格视图需要@model List<YourClass>并查看您的布局。

对于MVC中的Display GridView,有许多选项(免费和非免费)

DataTable示例

your Html for example
---------------------
<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
            </tr>
        </thead>
        <tbody>
            @foreach(var item in Model)
            <tr>
                <td>@item.Name</td>
                <td>@item.Position</td>
            </tr>
         <tbody>
    </table>


<script type="text/javascript" charset="utf8" src="//code.jquery.com/jquery-1.12.3.js"></script> 
<script type="text/javascript" charset="utf8"  src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> 
 <script> 
      $(document).ready(function () { 
         $('#example').DataTable(); 
       }); 
 </script>