0

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
  • 1
    The easiest way is to clone table and then delete columns not in the selection list. Commented Sep 19, 2019 at 14:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.