how to access querystring in ASP.Net MVC View?

asp.net MvcRazor

asp.net Mvc Problem Overview


How do I access the querystring value in a View?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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.

Solution 2 - asp.net Mvc

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"]

Solution 3 - asp.net Mvc

In .Net Core:

@Context.Request.Query["SomeParameter"]

Solution 4 - asp.net Mvc

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"){ ... }

Solution 5 - asp.net Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFraz SundalView Question on Stackoverflow
Solution 1 - asp.net MvcDarin DimitrovView Answer on Stackoverflow
Solution 2 - asp.net MvcChiragView Answer on Stackoverflow
Solution 3 - asp.net MvcShadi NamroutiView Answer on Stackoverflow
Solution 4 - asp.net MvcdougczarView Answer on Stackoverflow
Solution 5 - asp.net MvcalexView Answer on Stackoverflow