使用 URL.Action 帮助器和 javascript 变量的正确编码生成 URL

Generating URL with URL.Action helper and proper encoding of javascript variables

我正在尝试使用 Url.Action 帮助程序生成的 URL 和 AJAX 调用 ASP.MVC 中的操作方法。我有一些参数是使用 jQuery.

从 DOM 中提取的 javascript 变量

我试过两种方法都失败了。

我仅使用两个变量简化了示例。在现实世界中有四个(十进制?,字符串,字符串,字符串)。

第一个:

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name)';
link = link + '?first=' + first + '&second=' + second;

在这种情况下,所有参数都传递给 action 方法,但是当变量包含一些非标准字符(例如“é”)时,它的格式是错误的,我无法恢复它的正确编码(例如 "Simplifi�s" 而不是 "Simplifiés")

第二个:

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name, new { first = "-1", second = "-2"})'

link = link.replace("-1", first);
link = link.replace("-2", second);

在这种情况下,只有第一个变量(可为空的十进制)传递给操作方法。其余为空字符串。

我注意到在第二种情况下 link 看起来像这样:

/ControlerName/Edit?first=890 &amp ;second=Something

(插入 890 和 ;second 之间的空格只是因为堆栈溢出的 html 渲染)

而在第一种情况下,它看起来如下:

/ControlerName/Edit?first=890&second=Something

操作方法如下:

[HttpGet]
public virtual ActionResult Edit(decimal? first, string second)
{
   //code
}

Ajax 调用如下所示:

$.ajax({
    url: link,
    type: 'get',
    cache: false,
    async: true,
    success: function (result) {
        $('#someId').html(result);
    }
});

变量选自DOM如下:

var first = $(this).closest('tr').find('.first').html();

@Url.Action 将为您的基础 url 进行必要的编码,但您必须为您的 2 javascript 变量 first 和处理 url 编码second自己一个人。

一种直接的方法是使用 encodeURIComponent():

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name)';
link = link 
       + '?first=' + encodeURIComponent(first) 
       + '&second=' + encodeURIComponent(second);

或者正如@Nilesh 在评论中提到的那样,您可以一次性使用 encodeURI()

var link = '@Url.Action(MVC.ControllerName.ActionNames.Edit, MVC.ControllerName.Name)';
link = link + '?first=' + first + '&second=' + second;
linkToUse = encodeURI(link);