Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
Rasmita Dash Avatar asked Feb 04 '15 08:02

Rasmita Dash


5 Answers

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)
like image 122
vinayan Avatar answered Nov 15 '22 21:11

vinayan


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 .......
}
like image 37
Rush.2707 Avatar answered Nov 15 '22 23:11

Rush.2707


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 .......
}
like image 35
Ali Mahdian Avatar answered Nov 15 '22 23:11

Ali Mahdian


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/

like image 1
malkam Avatar answered Nov 15 '22 21:11

malkam


  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })
like image 1
raju soneri Avatar answered Nov 15 '22 21:11

raju soneri