【问题标题】:Generating URL with URL.Action helper and proper encoding of javascript variables使用 URL.Action 帮助器和正确的 javascript 变量编码生成 URL
【发布时间】:2015-01-12 12:35:33
【问题描述】:

我正在尝试使用 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;

在这种情况下,所有参数都传递给操作方法,但是当变量包含一些非标准字符(例如“é”)时,它的格式不正确,并且我在恢复它的正确编码时遇到问题(例如“简化”而不是“简化”)

第二:

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);

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

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

/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();

【问题讨论】:

  • 也许使用 post 类型将包含一些非标准字符的字符串发送到服务器?
  • 你为什么不使用Server.UrlEncodeServer.UrlDecode
  • @Nilesh 我不知道我应该这样做。对不起。现在我用UrlEncode包围了Url.Action,但是AJAX找不到action方法……有什么窍门吗?
  • 你不应该用UrlEncode包围Url.ActionUrl.Action 本身将为您进行必要的编码,UrlEncode 将对您的 url 格式良好的基本 url 进行不必要的编码。你必须手动编码的部分是你的javascript变量firstsecond,用javascript编码函数encodeURIComponent()包围它们
  • 抱歉@Landeeyo 昨天无法回复。 @tweray 说的对,改用encodeURI

标签: javascript jquery ajax asp.net-mvc


【解决方案1】:

@Url.Action 将为您的基本 url 进行必要的编码,但您必须自己处理 2 个 javascript 变量 firstsecond 的 url 编码。

一种直接的方法是使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多