55

How do I access the querystring value in a View?

2
  • never heard of anyone having the need to do such thing in asp.net mvc, probably you want to access it an Action cuz that's going to be really easy
    – Omu
    May 22, 2010 at 12:46
  • 1
    Are you sure you need query strings in MVC? Maybe give an example of what you want.
    – H H
    May 22, 2010 at 12:46

5 Answers 5

68

It is not a good design to access query parameters in a view. The view should use the model provided by the controller. So the controller reads query parameters and passes them to the view. If you want to ignore this rule you could always do this in your view:

<%= Request["SomeParameter"] %>

But I would strongly discourage you from doing so.

0
25

In View, you can access it directly. No need to write any code in Controller, though you can.

For example - If your querystring has parameter named id, something like ?id=1

Razor syntax:

@Request.QueryString["id"]
1
  • 3
    Error CS0103 The name 'Request' does not exist in the current context
    – Jonnie
    Jul 2, 2019 at 8:03
12

In .Net Core:

@Context.Request.Query["SomeParameter"]
8

I would read the querystring value in your Controller, and then set that value to a property in your ViewBag. The ViewBag property can then be read in from your view.

e.g:

ViewBag.MyQSVal = Request.QueryString["myValue"];

Then, in your View:

@if(ViewBag.MyQSVal == "something"){ ... }
0

As Darin suggested you should not use Querystring in view. But one thing is you can access Request variable in your view because its Asp.Net and if you access it you have all the functions and member that are present there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.