Question

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.

Était-ce utile?

La solution 2

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.

Autres conseils

You should be definetly doing this in your controller, making it return an ActionResult and returning a RedirectResult, i.e.:

public ActionResult Search(string searchCriteria) {
    return Redirect("~/Views/Search/Result.cshtml?searchCriteria="+searchCriteria);
}

Btw, I'd also say don't use neither of the Request stuff (or even Redirects), but actions with parameters that MVC will bind automagically from POST or GET parameters. E.g, "www.something.com/search?searchCriteria=hello" will automatically bind the searchCriteria parameter to the Action handling /search. Or, "www.something.com/search/hello" will bind to the parameter defined into your Routing config.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top