77

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Shaokan
  • 7,438
  • 15
  • 56
  • 80

5 Answers5

180

You can use the following:

Request.Params["paramName"]

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

Community
  • 1
  • 1
Wouter Simons
  • 2,856
  • 1
  • 19
  • 15
42

I've found the solution in this thread

@(ViewContext.RouteData.Values["parameterName"])
Community
  • 1
  • 1
Daniel
  • 9,312
  • 3
  • 48
  • 48
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
  • 1
    That'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
  • 1
    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. – Jamie Dixon Jun 29 '11 at 00:09
  • 2
    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: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