hope someone can help because I’ve been racking my brains for the best part of yesterday evening! Basically, I’m trying to get a search form working using HttpGet so I can potentially retrieve results from an external source via the URL like:
http://url.com/Area/Controller/Action/SearchCategory/SearchCriteria
I create and pass a model to my view containing two properties for SearchCategory and SearchCriteria and have the associated HTML controls in the view. This works perfectly if I choose both a category AND enter something for my criteria. However, if I don’t enter anything in my criteria I get an infinite redirect. My route for this particular feature looks like this:
context.MapRoute(
"Dashboard-Search",
"Area/Controller/Action/{SearchCategory}/{SearchCriteria}",
new {
controller = "Controller",
action = "Action",
SearchCategory = "",
SearchCriteria = ""
}
);
I do have my model implementing IValidateableObject and validate that something has been entered, but obviously the route binding is done before anything can be validated.
Any ideas???
Routes
context.MapRoute(
"Dashboard-Search-NoCriteria",
"HEP/Dashboard/Search/{category}",
new { controller = "Dashboard", action = "Search", category = "Case No" }
);
context.MapRoute(
"Dashboard-Search",
"HEP/Dashboard/Search/{category}/{criteria}",
new { controller = "Dashboard", action = "Search", category = "Case No", criteria = "" }
);
Controller Action
[HttpGet]
public ActionResult Search(string SearchCategory, string SearchCriteria)
{
// create new instance of model and add search criteria so entered
// data persists on post back
DashboardModel model = new DashboardModel() {
SearchCategory = SearchCategory,
SearchCriteria = SearchCriteria
};
model.Search(SearchCategory, SearchCriteria);
// return the HTML view of another controller that displays the same list,
// only this time, the list is filtered according to GET data
return View("Overview", model);
}
HTML Form
@using (Html.BeginForm("Search", "Dashboard", FormMethod.Get)) {
@Html.LabelFor(m => m.SearchCategory, "Category:")
@Html.DropDownListFor(m => m.SearchCategory, new List<SelectListItem>() {
new SelectListItem() { Selected = true, Text = "Category", Value = "Category" }
})
@Html.LabelFor(m => m.SearchCriteria, "Criteria:")
@Html.TextBoxFor(m => m.SearchCriteria)
<input type="submit" value="Search" class="button" />
}
Your routes right now do not correspond to your search form.
URL that satisfies your
Dashboard-Searchroute should look likeYour form in turn will produce a GET request to URL like this:
Most probably your method
Search(string SearchCategory, string SearchCriteria)is not ever called – I’d suggest that your request is redirected back to the method which is just showing your search view without actually performing any search.Please show the entire RegisterRoutes method if you need more explanations or code.