How to pass multiple parameters from ajax to mvc controller?

Rasmita Dash picture Rasmita Dash · Feb 4, 2015 · Viewed 113.7k times · Source

Controller

[HttpPost]
public ActionResult Save(string StrContactDetails, bool IsPrimary)
{
}

$.ajax({
  async: true,
  type: "POST",
  url: @url.Action("Helper","Save"),
  data: {
    StrContactDetails: Details,
    IsPrimary: true
  },
  //data: "StrContactDetails=" + Details + "&IsPrimary=" + true,
  //data: "{StrContactDetails:'" + Details + "',IsPrimary:"+ true + "}",
  //contentType: "application/json; charset=utf-8",
  success: function() {
  },
  error: function() {
  }
});

This works when my action method expects a single parameter and I pass the single parameter from ajax. But, I am unable to call the action with two parameters when it expects two parameters. So, there is some issue in passing parameters. May be content Type.

routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Default", action = "Login", id = UrlParameter.Optional }
).DataTokens = new RouteValueDictionary(new { area = "MyArea" });

I can call .../TestProj/MyArea/Helper/Save/StrContactDetails="Test" when my action method is as follows.

public ActionResult Save(string StrContactDetails)
{
  return Content("called");         
}

I can call .../TestProj/MyArea/Helper/SaveEmergencyContact/StrContactDetails="test"?IsPrimary=true if my action method is as follows. But I am getting 404 for .../TestProj/MyArea/Helper/SaveEmergencyContact/StrContactDetails="test"/IsPrimary=true (replace ? with /)

public ActionResult Save(string StrContactDetails, bool IsPrimary)
{
  return Content("called");         
}

What I am missing here? Do I need to make route config change for ajax call with 2 parameters?

Answer

vinayan picture vinayan · Feb 4, 2015

I think you may need to stringify the data using JSON.stringify.

 var data = JSON.stringify({ 
                 'StrContactDetails': Details,
                 'IsPrimary':true
               });

$.ajax({
        type: "POST",
        url: @url.Action("Dhp","SaveEmergencyContact"),
        data: data,
        success: function(){},
        contentType: 'application/json'
    });

So the controller method would look like,

public ActionResult SaveEmergencyContact(string  StrContactDetails, bool IsPrimary)