Search code examples
c#asp.net-mvc-4response.redirectrequest.querystring

Alternative to Response.Redirect with Request.Querystring


I've made a mvc4 project in Visual Studio Express 2012 for web. And there I've made a search function. And a view to show the result.

So normally I would have added this to the _Layout.cshtml.

if (Request["btn"] == "Search")
{
    searchValue = Request["searchField"];

    if (searchValue.Length > 0)
    {
        Response.Redirect("~/Views/Search/Result.cshtml?searchCriteria=" + searchValue);
    }
}

And that doesn't work. What whould be the alternative to Response.Redirect in mvc4, which still allows me to keep the searchCriteria to be read with Request.Querystring at the Result.cshtml page.


Solution

  • A simple example would be something like this:

    Index.cshtml:

    @using (Html.BeginForm("Results", "Search", FormMethod.Get))
    {
        @Html.TextBox("searchCriteria")
        <input type="submit" value='Search' />
    }
    

    Then the controller:

    public class SearchController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        public ActionResult Results(string searchCriteria)
        {
            var model = // ... filter using searchCriteria
    
            return View(model);
        }
    }
    

    model could be of type ResultsViewModel, which would encase everything you need to display the results. This way, your search is setup in a RESTful way - meaning it behaves consistently each time.