如何将c#变量绑定到HTML
本文关键字:绑定 HTML 变量 | 更新日期: 2023-09-27 18:15:26
我已经从控制器中的SQL查询创建了一个DataTable。
我如何"连接"'#example'与'categories'?
EDIT1:建议使用jQuery。datatable
@{
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>
原来
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>
首先,我建议你不要把所有东西都放在一个视图中,为Grid创建视图,为@model List<YourClass>
创建视图,为布局创建视图。
在MVC中显示GridView,有许多选项(免费和非免费)
- https://www.datatables.net/
- https://demos.telerik.com/aspnet-mvc/grid
- https://demos.devexpress.com/MVCxGridViewDemos/
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>