【问题标题】:MVC ASP.NET querystring incorrectMVC ASP.NET 查询字符串不正确
【发布时间】:2014-03-27 13:46:55
【问题描述】:

我的查询字符串有问题,我在控制器中使用这样的 javascript 调用一个操作

if ((event >= 65) && (event <= 90) || (event >= 48) && (event <= 57)) {
    var focussed = document.activeElement.id;
    window.setTimeout(function () {
        alert(in2.value);
        location.href = "/CarSaldi/ListaArt?in1=" + in1.value + "&in2=" + in2.value + "&focus=" + focussed;
    }, 1000);
}

in2 是输入文本,当我在控制器中调用操作时,其中可能有一个“+”(例如“milk+chocolate”)

public ActionResult ListaArt(string in1, string in2, string cod, string focus)
{
    [...]
}

字符串 in2 显示我的“牛奶巧克力”,我希望牛奶+巧克力......我还需要里面有“+”。

【问题讨论】:

标签: c# javascript asp.net asp.net-mvc


【解决方案1】:

使用 javascript 函数 encodeURIComponent:

编码您的字符串

你可以使用:

 encodeURIComponent(in1.value)

【讨论】:

    【解决方案2】:

    永远,永远,永远不要使用 javascript 和字符串连接在 asp.net mvc 中构造您的查询字符串。总是让这个给Url.Action。主要原因是查询字符串上留下的内容和路径信息中的内容取决于您的路线是如何定义的。如果您想让自己有机会在未来轻松更改路线,请始终使用Url.Action

    var uri = "@Url.Action("ListaArt", CarSaldi", new {in1="xxx", in2="yyy", focus="zzz"})".replace("&amp;","&");
    // Replace the "placeholders" values to the real ones
    uri = uri.replace("xxx", in1.value);
    uri = uri.replace("yyy", in2.value);
    uri = uri.replace("yyy", focussed);
    location.href = uri;
    

    关于加号,您需要在 Javascript 中使用 encodeURIComponent 方法:

    uri = uri.replace("yyy", encodeURIComponent(in2.value));
    

    希望这会有所帮助!

    PS:replace("&amp;amp;","&amp;") 是必需的,因为Url.Action 使用 & 而不是 & 生成 URL 来分隔查询字符串的标记。这对 HTML 有好处(您可以将其放在 A 标签的 href 中),但不适用于 location.href 属性。

    【讨论】:

      【解决方案3】:

      使用encodeURIComponent(yourParameter)

      在这种情况下特殊字符不会丢失

      【讨论】:

        【解决方案4】:

        你应该使用java脚本函数encodeURIComponent来编码url。

        location.href = "/CarSaldi/ListaArt?in1=" + encodeURIComponent(in1.value) 
         + "&in2=" + encodeURIComponent(in2.value) + "&focus=" + encodeURIComponent(focussed);
        

        你需要改变你的代码如下

        if ((event >= 65) && (event <= 90) || (event >= 48) && (event <= 57)) {
        var focussed = document.activeElement.id;
        window.setTimeout(function () {
            alert(in2.value);
            location.href = "/CarSaldi/ListaArt?in1=" + encodeURIComponent(in1.value) 
         + "&in2=" + encodeURIComponent(in2.value) + "&focus=" + encodeURIComponent(focussed);
          }, 1000);
        }
        

        【讨论】:

          【解决方案5】:

          加号应在您的情况下进行 URL 编码:

           +   =  %2B
          

          所以不要在 URL 中使用 '+' 使用 '%2B'

          查看完整的 URL 编码字符表:http://www.degraeve.com/reference/urlencoding.php

          【讨论】:

          • 所以我可以用 %2b 替换 javascript
          • @theLaw 是的,例如
          • @theLaw 最好使用内置 encodeURIComponent(string) 函数
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多