Filtering a List view in an ASP.MVC application
I would like to implement filtering in a List view based on the value in a DropDownList, in a sort of 'postback' call, where the user selects dropdown values and clicks a Refresh button. I have figured out that I should use my ViewData for the model being listed, but how do I pass the selected values back to the Index override that takes filter p开发者_C百科arameters?
Why not put your dropdown in a form that has GET as it's method. You would then generate a URL that looks like http://mysite.com/controller/action/?filterView=ByName
This allows your end users to bookmark their filtered results for quick reference. You could also create a new route if you didn't want the ? in the URL.
Your controller would be something similar to below (up to you to define your filtering logic as I don't know if you are doing date ranges, getting rid of duplicates, whatever). This assumes you are filtering by a column.
public ActionResult Index(string filterView = "")
{
var items = _repository.getItems();
// filter you items based on the filterView string
if (!string.IsNullOrEmpty(filterView ))
{
//do your filtering logic here
items = items.where(c=>c.FilterColumn = filterView);
}
//return the view with the items that result from the above operation or
//just the full list if no filtering was done
return View(items);
}
Using the Routing API. You can configure a new route in your Global.asmx.cs
that means that calls to the Index action on your controller with a certain URL format will be sent to the correct controller.
It might just work as long as the name of the parameter submitted matches the name of parameters in your action method, but I'm less sure of that.
ProfK - you could do it a couple of ways, tho i note that you mention a 'sort of postback' approach. in this case, you'd be best to do exactly that - postback the filter values and 'parse' them in the controller index method. something along the lines of this might be an approach:
public ActionResult Index()
{
string sComboValPerson = Request.Form["personfilter"];
// now do something with this value if it is't null
if (!string.IsNullOrEmpty(sComboValPerson ))
{
var items = _repository.Search(Model, sComboValPerson );
return View(items);
}
else
// return some kind of not found content or the 'normal' view
return View();
}
精彩评论