5

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"
            , 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?

DaveDev
  • 41,155
  • 72
  • 223
  • 385

2 Answers2

1

ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?

Community
  • 1
  • 1
takepara
  • 10,413
  • 3
  • 34
  • 31
0

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();
      }
   }

   ...
}
Fabiano
  • 5,124
  • 6
  • 42
  • 69