我是ASP.NET新手并尝试构建购物应用。我正在使用jquery.datatable和ajax来显示表中商店中的所有商品:
@model IEnumerable<OnlineShoppingApp.Models.Category>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="col-md-2">
<ul id="categories">
@foreach(var category in Model)
{
<li data-category-id="@category.Id">@category.Name</li>
}
</ul>
</div>
<div class="col-md-10">
<table id="items" class=" table table-bordered table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Category</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
@section Scripts {
<script>
$(document).ready(function () {
$("#items").DataTable(
{
ajax:
{
url: "/api/items",
dataSrc: ""
},
columns:
[
{
data: "Name",
},
{
data: "Description",
},
{
data: "Price",
},
{
data: "Category.Name",
}
]
}
)
$("li").click(function () {
var element = $(this);
});
});
</script>
}
在CategoryController中:
public ActionResult Index()
{
var categories = context.Categories.ToList();
return View(categories);
}
在左侧,我列出了所有类别,当点击其中一个我想过滤此数据表时,只显示与所选类别匹配的项目。我不希望页面重新加载,我不知道从哪里开始。
答案 0 :(得分:0)
您只需在布局中添加以下CSS和js文件
//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css
//cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js
<script>
$(document).ready(function () {
$("#items").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": false, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/api/items",
"type": "POST",
"datatype": "json"
},
"columns": [
{ "data": "Name", "name": "Name", "autoWidth": true },
{ "data": "Description", "name": "Description", "autoWidth": true },
{ "data": "Price", "name": "Price", "autoWidth": true },
{ "data": "CategoryName", "name": "CategoryName", "autoWidth": true }
]
});
});
</script>
[HttpPost]
public ActionResult items()
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//Find Order Column
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
int pageSize = length != null? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var v= context.Categories.ToList();
//SORT
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
v = v.OrderBy(sortColumn + " " + sortColumnDir);
}
recordsTotal = v.Count();
var data = v.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = data }, JsonRequestBehavior.AllowGet);
}