Best way to filter a list-view in asp.net MVC
I have a list of data coming from the database and displaying in a table, that works exactly how I want.
What I would like to do, is add a DropDownList to the page that "filters" the data in the table, based on the value of the selected item in the DropDonwList.
For example, the DropDown has these values
Assigned To Me
Assigned To Others
and the list of data, has an "assignedTo" field. When the value in the dropdow开发者_如何转开发n changes, I would like to update the list of data.
In WebForms, I would use an UpdatePanel and a DropDownList with autoPostBack=True, how can I get the same effect in MVC?
You use JavaScript/jQuery to bind to onchange/onclick event, and there do a postback:
$(function() {
$("#myelement").click(function(){
$("#secondelement").load('<%= Url.Action("Source") %>?selected=' + $(this).val());
});
}
There're jQuery plugins that do similar things, for example http://dev.chayachronicles.com/jquery/cascade/index.html (not the best one, the first I found).
You have a few options. One way is to create a Controller method that manages the process of grabbing your data (say as a IList), and then uses the Json(...) method of the Controller to serialize it and send it back as JsonResult (here's an example: http://weblogs.asp.net/mehfuzh/archive/2009/04/28/using-of-json-result-in-asp-net-mvc-1-0.aspx).
On your front end, you can wire up some javascript on the dropdown list that uses jQuery to make a $.get (http://api.jquery.com/jQuery.get/) passing back an id of sorts to determine your filter criteria.
Then you use the callback function of the $.get(...) call to manipulate your DOM as you see fit to visually depict the new list of data.
精彩评论