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
You can use the following:
Request.Params["paramName"]
I've found the solution in this thread
@(ViewContext.RouteData.Values["parameterName"])
1 Comment
jaypeagi
This will only work if the query string parameter is also a parameter on the action.
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
Shaokan
yes but my question is whether I can get it directly from the View, without using the controller?
Jamie Dixon
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?
Shaokan
That's an habit, in general I try to avoid ViewBags in favor of Model.
Jamie Dixon
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.
Alexandra
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)
|
@(HttpUtility.UrlDecode(Request.Query["parameterName"].FirstOrDefault()) ?? "")
1 Comment
Tyler2P
Your answer could be improved by adding more information on what the code does and how it helps the OP.