79

Why does Request["parameterName"] returns null within the view? I know I can get it from the controller but I have to make a little check in the View. I am using ASP.NET MVC 3.

6 Answers 6

184

You can use the following:

Request.Params["paramName"]

See also: When do Request.Params and Request.Form differ?

Sign up to request clarification or add additional context in comments.

2 Comments

Nice! Worked! you have my +1! :)
This only works for parameters which are after "?", not for route parameters.
43

I've found the solution in this thread

@(ViewContext.RouteData.Values["parameterName"])

1 Comment

This will only work if the query string parameter is also a parameter on the action.
10
@(ViewContext.RouteData.Values["parameterName"])

worked with ROUTE PARAM.

Request.Params["paramName"]

did not work with ROUTE PARAM.

Comments

6

If you're doing the check inside the View, put the value in the ViewBag.

In your controller:

ViewBag["parameterName"] = Request["parameterName"];

It's worth noting that the Request and Response properties are exposed by the Controller class. They have the same semantics as HttpRequest and HttpResponse.

7 Comments

yes but my question is whether I can get it directly from the View, without using the controller?
You've already stated that Request["parameterName"] returns null in your view. Your question seemed more about making a check in the View, which you can do using this solution. What's stopping you from wanting to use the ViewBag?
That's an habit, in general I try to avoid ViewBags in favor of Model.
The Request object is a property of the Controller class. I may be mistaken, but I dont think the view has access to that property of the Controller class.
For those of you who get an exception "Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'", just replace ViewBag with ViewData (source:forums.asp.net/t/1800747.aspx/1)
|
2

.Net Core 7 @Requst.Query["ParamName"]

Comments

1
@(HttpUtility.UrlDecode(Request.Query["parameterName"].FirstOrDefault()) ?? "")

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

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.