Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 943
AMeh Avatar asked Dec 02 '15 02:12

AMeh


People also ask

How do I pass multiple parameters in URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

How do you pass dynamic values in URL action?

You can concat the client-side variables with the server-side url generated by this method, which is a string on the output. Try something like this: var firstname = "abc"; var username = "abcd"; location. href = '@Url.

Can one action method have multiple views?

Yes, completely possible. And, it can be multiple views, or even a FileResult or other result type.


2 Answers

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;
}
like image 66
simdrouin Avatar answered Oct 30 '22 05:10

simdrouin


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;
like image 26
Shyju Avatar answered Oct 30 '22 06:10

Shyju