我根据您的需要做了一个测试,下面是一个工作演示:
看法:
@model IEnumerable<Product>
@{
List<SelectListItem> listItems = new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Active",
Value = "Active"
});
listItems.Add(new SelectListItem
{
Text = "Deactivated",
Value = "Deactivated"
});
}
<table id="mytable" class="table table-striped table-bordered dt-responsive nowrap" width="100%" cellspacing="0">
<thead>
<tr>
<td>
@Html.DisplayNameFor(model => model.Id)
</td>
<td>
@Html.DisplayNameFor(model => model.Name)
</td>
<td>
@Html.DropDownList("Status", listItems, "Status")
</td>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@(item.Status ? "Active" : "Deactivated")
</td>
</tr>
}
</tbody>
</table>
@section scripts{
<script>
$("#Status").on('change', function () {
var val = $("#Status option:selected").text();
$.ajax({
type: 'get',
url: '/Home/FilterByStatus',
data: { status: val },
success: function (result) {
$("#mytable tbody").empty();
$.each(result, function (i, value) {
$("#mytable tbody").append("<tr><td>" + value.id + "</td><td>" +
value.name + "</td><td>" + (value.status ? "Active" : "Deactivated") +"</td></tr>")
})
}
})
})
</script>
}
控制器:
public static List<Product> products = new List<Product>
{
new Product{ Id = 1, Name = "AA", Status = true},
new Product{ Id = 2, Name = "BB", Status = true},
new Product{ Id = 3, Name = "CC", Status = false},
new Product{ Id = 4, Name = "DD", Status = false}
};
public IActionResult Index()
{
return View(products);
}
public IActionResult FilterByStatus(string status)
{
var filterproducts = products.ToList();
if (status == "Active")
{
filterproducts = products.Where(p => p.Status == true).ToList();
return Json(filterproducts);
}
else if(status == "Deactivated")
{
filterproducts = products.Where(p => p.Status == false).ToList();
return Json(filterproducts);
}
return Json(filterproducts);
}
结果:
