AMeh
AMeh

Reputation: 211

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

I have below javascript function in my MVC application,

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?

Upvotes: 6

Views: 21024

Answers (3)

user2872726
user2872726

Reputation: 1

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

Upvotes: 0

simdrouin
simdrouin

Reputation: 1018

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

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

Upvotes: 15

Shyju
Shyju

Reputation: 218952

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

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;

Upvotes: 3

Related Questions