How to get query string parameter from MVC Razor markup?

I want to check the URL parameter in my Razor markup. For example, how do I do something like this:

<div id="wrap" class="@{if (URL "IFRAME" PARAMETER EQUALS 1) iframe-page}"> 
+59
c # asp.net-mvc razor asp.net-mvc-4
Jun 28 '12 at 15:36
source share
6 answers

Similar topic

 <div id="wrap" class=' @(ViewContext.RouteData.Values["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div> 

EDIT 01-10-2014: Since this question is so popular, this answer has been improved.

In the above example, only values ​​from RouteData , that is, only from RouteData strings that are intercepted by any registered route. To get the value of the query string, you must go to the current HttpRequest . The fastest way is to call (as TruMan pointed out) "Request.Querystring", so the answer should be:

 <div id="wrap" class=' @(Request.QueryString["iframe"] == 1 ? /*do sth*/ : /*do sth else*/')> </div> 

Can you also check RouteValues ​​against QueryString MVC?

EDIT 05-05-2019: The above solution works for the .NET Framework.
As others noted, if you want to get the value of a query string in .NET Core, you should use the Query object from the Context.Request path. So it would be:

 <div id="wrap" class=' @(Context.Request.Query["iframe"] == new StringValues("1") ? /*do sth*/ : /*do sth else*/')> </div> 

Note that I use StringValues("1") in the expression because Query returns a StringValues object instead of a pure string . This clears the path for this script that I found.

+90
Jun 28 2018-12-12T00:
source share

If you are using .net core 2.0, this will be:

 Context.Request.Query["id"] 

Usage example:

 <a href="@Url.Action("Query",new {parm1=Context.Request.Query["queryparm1"]})">GO</a> 
+18
Jan 31 '18 at 9:01
source share

I think a more elegant solution is to use a ViewData controller and dictionary:

 //Controller: public ActionResult Action(int IFRAME) { ViewData["IsIframe"] = IFRAME == 1; return View(); } //view @{ string classToUse = (bool)ViewData["IsIframe"] ? "iframe-page" : ""; <div id="wrap" class='@classToUse'></div> } 
+5
Jun 28 '12 at 15:41
source share

It was suggested that this be posted as an answer because some other answers lead to errors such as "The name context does not exist in the current context."

Just using the following works:

 Request.Query["queryparm1"] 

Usage example:

 <a href="@Url.Action("Query",new {parm1=Request.Query["queryparm1"]})">GO</a> 
+5
Apr 7 '18 at 14:21
source share

None of the answers worked for me, I got "HttpRequestBase" does not contain the definition of "Query", but it worked:

 HttpContext.Current.Request.QueryString["index"] 
+1
Apr 22 '18 at 0:10
source share

For Asp.net Core 2

 ViewContext.ModelState["id"].AttemptedValue 
+1
Oct 17 '18 at 12:41
source share



All Articles