【问题标题】:Get Query String Value in ASP.NET MVC在 ASP.NET MVC 中获取查询字符串值
【发布时间】:2020-06-18 14:34:44
【问题描述】:

我有这个网址

var url = "/test/Create/" + $("#hdnFlag").val() +"?CmpT="+"Ilim";
window.location.href = url;

在我的测试控制器中,我这样做是为了获取查询字符串值

 tM_PMO.Type = Request.QueryString["CmpT"];

但总是给我空值。

【问题讨论】:

  • 您是否在路由表中配置了任何自定义路由?
  • @Devilscomrade 我不明白你是从 mvc 开始的

标签: javascript c# asp.net-mvc


【解决方案1】:

GETPOST 类型之间存在差异。

Query string 可以通过GET 请求的 URL 读取。但是,当您发出POST 请求时,您无法读取 URL 中的查询字符串值。为此,您需要将其提交到服务器。

下面我给大家举几个例子。

GET 请求 您可以读取带有 URL 的查询字符串,如下所示

public ActionResult Test(string CmpT)
{
    if (!string.IsNullOrWhiteSpace(CmpT))
    {
        //your codes...
    }else
    { }
    return View();
}

POST 请求 如果您正在发出POST 请求并尝试从 URL 中读取,它将返回 null。为了读取它,您需要将该值发送到服务器,如下所示。

第一种方式:在您的 Html.BeginForm 在您的 View below 中,提交如下查询字符串并将此值作为 Action 参数读取

查看页面

@using (Html.BeginForm("Test", "XController", new { returnUrl = Request.QueryString["CmpT"] }, FormMethod.Post, new { role = "form" }))
{
    <button type="submit">Send</button>
}

控制器

public ActionResult Test(string returnUrl)
{
    if (!string.IsNullOrWhiteSpace(returnUrl))
    {
        //your codes...
    }else
    { }
    return View();
}

第二种方式:在视图页面中的 Html.BeginForm 标记之间创建一个隐藏的表单元素作为表单的一部分,并将其值作为查询字符串提供。然后在下面的 Action 方法中调用它。

查看页面

@using (Html.BeginForm("Test", "XController", FormMethod.Post, new { role = "form" }))
{
    @Html.Hidden("returnUrl", Request.QueryString["CmpT"])
    <button type="submit">Send</button>
}

控制器

public ActionResult Test(string returnUrl)
{
    if (!string.IsNullOrWhiteSpace(returnUrl))
    {
        //your codes...
    }else
    { }
    return View();
}

或用于多个表单项(您也可以通过这种方式访问​​其他表单元素)

public ActionResult Test(FormCollection fc)
{
    string _returnUrl = fc["returnUrl"];
    if (!string.IsNullOrWhiteSpace(_returnUrl))
    {
        //your codes...
    }else
    { }
    return View();
}

【讨论】:

    【解决方案2】:

    我希望您正在寻找下面的代码示例,我们只是获取 url 中的值,我们说 query string:

    Request.QueryString["querystringparamname"].ToString(); 
    

    您可以在任何Var 中分配它并相应地使用。

    【讨论】:

    • 答案有问题吗,我只是回答了,因为问题不清楚,我在看到问题时做出了这个回复。
    • 我没有否决您的答案,但我猜如果 OP 获得空值并且您最后添加了 .ToString(),它将引发错误 NullReferenceException。无法在空引用对象上调用方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多