I have a DataTable as a property to a ViewModel which I pass from the Controller Action to the View. In the MVC View, I have a select box in HTML. How can I filter the DataTable in the View on the change of selected option in the select box? In other words, consider that the DataTable consists of unique key columns and values. If I select option ABCD in select box, I should be able to apply ABCD as filter to the C# DataTable and retrieve the value from the DataTable.
1 Answer
Use onchange in select box, and post value selected through ajax to controller, in controller return the value filter list. Something like:
<select onchange="changeTable(this)">
<script>
function changeTable(val)
{
$.ajax({
url: '/yourcontroller/youraction',
type: "POST",
dataType: "json",
data: "selectedId": val.selectedId,
processData: false,
contentType: false,
success: function (data) {
table.DataTable(){data: data}
}
}
</script>
In controller,
public actionresult yourcontroller(int selectedId)
{
return Json(list.where(n=>n.Id == selectedId));
}
I think this will help you.
1 Comment
Bill Berlington
Thank you very much. I used your logic to filter it from the controller. I have accepted this as answer for now. I was hoping I could do that in the View itself instead of calling the controller.