AnonyMouse
AnonyMouse

Reputation: 18630

How to access a query string in MVC

I was getting the query string back using:

public ActionResult Index(int id)
{
  var queryString = Request["myQueryString"];
}

Then I looked at:

help-testing-mvc3-controller-that-accesses-querystring

Which states:

It is against MVC's design pattern to use HttpRequest directly. You can access the query string variables on your action as parameters.

I don't really understand this. Is what I've done against the design pattern? If it is why is that and how could it be done?

Upvotes: 0

Views: 292

Answers (3)

Joey Gennari
Joey Gennari

Reputation: 2361

The preferred (and easier to read) method would be:

public ActionResult Index(int id, string myQueryString)
{
    ...
}

Upvotes: 1

Chris Knight
Chris Knight

Reputation: 1476

Your action method should take most of the data submitted from your form. One of the strengths of MVC is the model binding it has within it. Check out this page, as it has a good example of this:

http://www.codeproject.com/Articles/159749/ASP-NET-MVC-Model-Binding-Part1

You can accept literals (string, bool, etc.) but also strongly typed objects in your action methods.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190897

It breaks the concept of model binding. It also gets complicated with unit testing and trying to new up a new HttpContext for a test. If it was just a parameter, you could just pass the value.

Upvotes: 1

Related Questions