[jquery] How to pass multiple parameters from ajax to mvc controller?

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?

This question is related to jquery asp.net-mvc asp.net-ajax

The answer is


Try this:

var req={StrContactDetails:'data',IsPrimary:'True'}

$.ajax({
                   type: 'POST',
                   data: req,
                   url: '@url.Action("SaveEmergencyContact","Dhp")',
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   data: JSON.stringify(req),
                   success: function (data) {
                       alert("Success");
                   },
                   error: function (ob, errStr) {
                       alert("An error occured.Please try after sometime.");
                   }
               });

http://api.jquery.com/jquery.ajax/


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)

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

function toggleCheck(employeeId) {
    var data =  'referenceid= '+ employeeId +'&referencestatus=' 1;
    console.log(data);
    $.ajax({
        type : 'POST',
        url : 'edit',
        data : data,
        cache: false,
        async : false,
        success : function(employeeId) {
            alert("Success");
            window.redirect = "Users.jsp";
        }
    });

}

You can do it by not initializing url and writing it at hardcode like this

//var url = '@Url.Action("ActionName", "Controller");

$.post("/Controller/ActionName?para1=" + data + "&para2=" + data2, function (result) {
        $("#" + data).html(result);
        ............. Your code
    });

While your controller side code must be like this below:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

this was simple way. now we can do pass multiple data by json also like this:

var val1= $('#btn1').val();  
var val2= $('#btn2').val(); 
$.ajax({
                    type: "GET",
                    url: '@Url.Action("Actionre", "Contr")',
                    contentType: "application/json; charset=utf-8",
                    data: { 'para1': val1, 'para2': val2 },
                    dataType: "json",
                    success: function (cities) {
                        ur code.....
                    }
                });

While your controller side code will be same:

public ActionResult ActionName(string para1, string para2)
{
   Your Code .......
}

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

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-ajax

How to pass multiple parameters from ajax to mvc controller? window.open with target "_blank" in Chrome Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method Disable asp.net button after click to prevent double clicking How can I convince IE to simply display application/json rather than offer to download it? How to send a model in jQuery $.ajax() post request to MVC controller method How to post ASP.NET MVC Ajax form using JavaScript rather than submit button How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET? jQuery $(document).ready and UpdatePanels? ASP.NET MVC controller actions that return JSON or partial html