如何在 MVC 中的 JavaScript 中的 url.action 中传递多个参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34034025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:09:41  来源:igfitidea点击:

How to pass multiple parameters in url.action in JavaScript in MVC?

javascriptasp.net-mvc

提问by AMeh

I have below javascript function in my MVC application,

我的 MVC 应用程序中有以下 javascript 函数,

function EditProducts(productId, orderId, employeeId, mode) 
{
    mode = "edit";
    debugger;
    var url = '@Url.Action("Index", "Home", new { productId = "__productId__", orderId = "__orderId__", employeeId = "__employeeId__", Mode = "__mode__"})';
    var params = url.replace('__productId__', productId).replace('__orderId__', orderId).replace('__employeeId__', employeeId).replace('__mode__', mode);
    window.location.href = params;
}

But it doesn't work. Here is my controller code by I am not getting any values in below vaiables,

但它不起作用。这是我的控制器代码,我在下面的变量中没有得到任何值,

public ActionResult Index(int productId, int orderId, int employeeId, string mode)
{
    return View();
}

Any ideas on how to pass multiple parameters through url.action?

关于如何通过 url.action 传递多个参数的任何想法?

回答by simdrouin

Use @Html.Raw to prevent the ampersand from being converted to &inside javascript code

使用@Html.Raw 防止 & 号被转换为&JavaScript 代码内部

function EditProducts(productId, orderId, employeeId, mode) 
{
    mode = "edit";
    debugger;
    var url = '@Html.Raw(Url.Action("Index", "Home", new { productId = "__productId__", orderId = "__orderId__", employeeId = "__employeeId__", Mode = "__mode__"}))';
    var params = url.replace('__productId__', productId).replace('__orderId__', orderId).replace('__employeeId__', employeeId).replace('__mode__', mode);
    window.location.href = params;
}

回答by Shyju

Get the base url to the action method using Url.Actionhelper method and add the querystring params to that.

使用Url.Actionhelper 方法获取 action 方法的基本 url并将查询字符串参数添加到其中。

This should work fine

这应该可以正常工作

$(function(){

  var productId = 23;
  var employeeId = 44;
  var orderId = 34;
  var mode = "tes";

  var url = '@Url.Action("Index", "Post")';
  url += '?productId=' + productId + '&orderId=' + orderId + 
                                            '&employeeId=' + employeeId + '&mode=' + mode;
  window.location.href = url;

回答by user2872726

Only Converted the numbers to string

仅将数字转换为字符串

 function EditRoles(companyid, roleid) {

            //debugger;

            var url = '@Html.Raw(Url.Action("EditRol", "Rol", new { companyID = "__companyid__", roleID = "__roleID__"}))';
            var params = url.replace('__companyid__', companyid.toString()).replace('__roleID__', roleid.toString());
            window.location.href = params;
        }