asp.net-mvc 如何在 ASP.Net MVC 视图中访问查询字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2888105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:19:49  来源:igfitidea点击:

how to access querystring in ASP.Net MVC View?

asp.net-mvcrazor

提问by Fraz Sundal

How do I access the querystringvalue in a View?

如何访问querystring视图中的值?

回答by Darin Dimitrov

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.

但我强烈建议您不要这样做。

回答by Chirag

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

在 View 中,您可以直接访问它。尽管可以,但无需在 Controller 中编写任何代码。

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

例如 - 如果您的查询字符串具有名为 id 的参数,则类似于 ?id=1

Razor syntax:

剃刀语法:

@Request.QueryString["id"]

回答by dougczar

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.

我会读取您的控制器中的查询字符串值,然后将该值设置为您的 ViewBag 中的一个属性。然后可以从您的视图中读入 ViewBag 属性。

e.g:

例如:

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

Then, in your View:

然后,在您的视图中:

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

回答by Shadi Namrouti

To perform this bad practicein .Net Core:

要在.Net Core 中执行这种不好的做法

@Context.Request.Query["SomeParameter"]

回答by alex

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

正如 Darin 建议的那样,您不应在视图中使用 Querystring。但有一件事是您可以在您的视图中访问 Request 变量,因为它是 Asp.Net,如果您访问它,您将拥有那里存在的所有功能和成员