如何从 MVC Razor 标记中获取查询字符串参数? [英] How to get query string parameter from MVC Razor markup?

查看:47
本文介绍了如何从 MVC Razor 标记中获取查询字符串参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查 Razor 标记中的 URL 参数.例如,我该如何做这样的事情:

解决方案

类似线程

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

编辑 01-10-2014:由于这个问题如此受欢迎,因此该答案已得到改进.

上面的例子只会从 RouteData 获取值,所以只能从某个注册路由捕获的查询字符串中获取.要获得查询字符串值,您必须获得当前的 HttpRequest.最快的方法是调用(正如 TruMan 指出的)`Request.Querystring' 所以答案应该是:

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

您还可以查看RouteValues vs QueryString MVC?

编辑 03-05-2019:以上解决方案适用于 .NET Framework.
正如其他人指出的那样,如果您想在 .NET Core 中获取查询字符串值,您必须使用 Context.Request 路径中的 Query 对象.所以应该是:

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

请注意我在语句中使用了 StringValues("1") 因为 Query 返回 StringValues 结构而不是纯 string.这是我发现的这个场景的清洁方式.

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

解决方案

Similar thread

<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.

The example above will only get the values from RouteData, so only from the querystrings which are caught by some registered route. To get the querystring value you have to get to the current HttpRequest. Fastest way is by calling (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>

You can also check RouteValues vs QueryString MVC?

EDIT 03-05-2019: Above solution is working for .NET Framework.
As others pointed out if you would like to get query string value in .NET Core you have to use Query object from Context.Request path. So it would be:

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

Please notice I am using StringValues("1") in the statement because Query returns StringValues struct instead of pure string. That's cleanes way for this scenerio which I've found.

这篇关于如何从 MVC Razor 标记中获取查询字符串参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆