MVC ASP.NET查询字符串不正确

时间:2014-02-25 11:14:05

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

我的查询字符串有问题,我在我的控制器中用这样的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显示我的“牛奶巧克力”,我预计牛奶+巧克力...我需要内部还有“+”。

5 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:2)

使用encodeURIComponent(yourParameter)

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

答案 2 :(得分:1)

在您的情况下,加号应该是URL编码:

 +   =  %2B

因此,不要在网址中使用“ + ”,而是使用“%2B

请参阅URL编码字符的完整表格:http://www.degraeve.com/reference/urlencoding.php

答案 3 :(得分:1)

使用 javascript函数 encodeURIComponent

对字符串进行编码

你可以使用:

 encodeURIComponent(in1.value)

答案 4 :(得分:-1)

从不,永远,永远不要使用javascript和字符串连接在asp.net mvc中构造您的查询字符串。始终将其发送到Url.Action。主要原因是查询字符串上的内容以及pathinfo内部的内容取决于路由的定义方式。如果您希望将来有机会轻松更改路线,请始终使用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;","&")因为Url.Action使用&amp;生成网址而不是&amp;用于分离查询字符串的标记。这适用于HTML(您可以将其放在A标记的href中),但不适用于location.href属性。