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.
Asked
Active
Viewed 1.5e+01k times
77
5 Answers
180
You can use the following:
Request.Params["paramName"]

Community
- 1
- 1

Wouter Simons
- 2,856
- 1
- 19
- 15
-
2Nice! Worked! you have my +1! :) – SrAxi Oct 03 '14 at 11:29
-
4This only works for parameters which are after "?", not for route parameters. – Cosmin Nov 01 '17 at 10:32
42
I've found the solution in this thread
@(ViewContext.RouteData.Values["parameterName"])
-
8This will only work if the query string parameter is also a parameter on the action. – jaypeagi Jul 22 '14 at 10:12
10
@(ViewContext.RouteData.Values["parameterName"])
worked with ROUTE PARAM.
Request.Params["paramName"]
did not work with ROUTE PARAM.

freedomn-m
- 27,664
- 8
- 35
- 57

Ravi Ram
- 24,078
- 21
- 82
- 113
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
.

Jamie Dixon
- 53,019
- 19
- 125
- 162
-
yes but my question is whether I can get it directly from the View, without using the controller? – Shaokan Jun 28 '11 at 23:45
-
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? – Jamie Dixon Jun 28 '11 at 23:48
-
1That's an habit, in general I try to avoid ViewBags in favor of Model. – Shaokan Jun 28 '11 at 23:58
-
Is this data part of the model though? From what you said, you simply want to check some condition in order to do something else? – Jamie Dixon Jun 28 '11 at 23:59
-
Either way, it seems odd that the values are different between view and controller - they should be referencing the same exact Request object. – eulerfx Jun 29 '11 at 00:08
-
1The 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. – Jamie Dixon Jun 29 '11 at 00:09
-
2For 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:http://forums.asp.net/t/1800747.aspx/1) – Alexandra Aug 22 '12 at 04:57
0
@(HttpUtility.UrlDecode(Request.Query["parameterName"].FirstOrDefault()) ?? "")

OrElse
- 9,709
- 39
- 140
- 253
-
Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 31 '22 at 08:47