I have the following block of code
public ActionResult Tabs(SearchViewModel svm)
{
if (Request.IsAjaxRequest())
{
svm.Summary = _entitySearchService.GetSearchDataSummary(svm.Search);
return PartialView(svm);
}
else
{
return RedirectToAction("QuickSearch", "Search"
开发者_Python百科 , new RouteValueDictionary { { "search", svm.Search } });
}
}
if the user submits a search that ends with a space, e.g. "something ", it works fine if it's an ajax request, but if it's not an ajax request, the request gets redirected to a different Action Method, at which point something goes wrong and a 404 is returned.
I could do a trim()
in the else
clause, e.g.
new RouteValueDictionary { { "search", svm.Search.Trim() } }
but there are a few places that this happens. Ideally I could do it all in the one place.
Would it be considered too hackish if I put it into the Controller's Initialize
method?
protected override void Initialize(RequestContext requestContext)
{
// do a test to see if there's a 'search' parameter in requestContext,
// and if so, trim it
base.Initialize(requestContext);
}
Or is there another better way?
ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?
You could override the setter of your SearchViewModel if this is an option
public class SearchViewModel
{
...
private string search;
public string Search
{
get
{
return search;
}
set
{
search = value.Trim();
}
}
...
}
精彩评论