3

In an MVC3 app, i have the following View:

@using (Html.BeginForm("Index", "Search", new {query = @Request.QueryString["query"]}, FormMethod.Post))
{
   <input type="search" name="query" id="query" value="" />
}

When i type in the url "/Search?query=test", Request.Querystring in my Index action reads out the search-value perfectly well (i have my routes set to ignore the Action in the url). When i type it in the seachbox, it hits the right action and controller (so the routing seems fine) but the querystring remains empty. What am i doing wrong?

1 Answer 1

4

The Problem is that you are look in the Request.QueryString collection. But you are doing a POST so the query value is in the Request.Form Collection. But i think you want your TextBox filled with the data so can do it like in my sample.

Sample

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
   <input type="search" name="query" id="query" value="@Request.Form["query"]" />
}

But this is not the real MVC approach. You should create a ViewModel for that.

Model

namespace MyNameSpace.Models
{
    public class SearchViewModel
    {
        public string Query { get; set; }
    }
}

View

@model MyNameSpace.Models.SearchViewModel

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
   @Html.TextBoxFor(x => x.Query)
   <input type="submit" />
}

Controller

public ActionResult Index()
{
    return View(new SearchViewModel());
}

[HttpPost]
public ActionResult Index(SearchViewModel model)
{
    // do your search
    return View(model);
}
Sign up to request clarification or add additional context in comments.

4 Comments

hi dknaack, thanks for ur quick reply.. im afraid changing the order order of the parameters doesnt make a difference..
hi dknaack, that did the trick! its in Request.Form. thanks! and for what do you mean i should make a ViewModel?
@jim it does. But the ViewModel solution is the real answer.
dknaack, thanks for your extensive reply. ill go and implement your real MVC example :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.