简体   繁体   English

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

[英]how to access querystring in ASP.Net MVC View?

如何访问视图中的querystring值?

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.但我强烈建议您不要这样做。

In View, you can access it directly.在 View 中,您可以直接访问它。 No need to write any code in Controller, though you can.尽管可以,但无需在 Controller 中编写任何代码。

For example - If your querystring has parameter named id, something like ?id=1例如 - 如果您的查询字符串具有名为 id 的参数,则类似于 ?id=1

Razor syntax:剃刀语法:

@Request.QueryString["id"]

I would read the querystring value in your Controller, and then set that value to a property in your ViewBag.我会读取您的控制器中的查询字符串值,然后将该值设置为您的 ViewBag 中的一个属性。 The ViewBag property can then be read in from your view.然后可以从您的视图中读入 ViewBag 属性。

eg:例如:

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

Then, in your View:然后,在您的视图中:

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

.Net 核心中

@Context.Request.Query["SomeParameter"]

As Darin suggested you should not use Querystring in view.正如 Darin 建议的那样,您不应在视图中使用 Querystring。 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但有一件事是您可以在您的视图中访问 Request 变量,因为它是 Asp.Net,如果您访问它,您将拥有那里存在的所有功能和成员

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM