ManInMoon ManInMoon - 1 month ago 7
jQuery Question

How to bind c# variable to HTML

I have created a DataTable from a SQL query in the the controller.

How do I "connect" '#example' with 'categories'?


EDIT1: After suggestion to use 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>

Answer

First, I recommend to you not to put everyrthing in one view, Create View for Grid take @model List<YourClass> and View for your Layout.

For Display GridView in MVC, There are many options (Free and not-free)

DataTable Example

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>