22

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?

8
  • 1
    Change it to data: { StrContactDetails: 'Details', IsPrimary: 'true' }, (or use JSON.stingfy() ) Commented Feb 4, 2015 at 8:54
  • Does it hit your action method, but provide null parameters? Commented Feb 4, 2015 at 8:54
  • No it's not hitting Action method Commented Feb 4, 2015 at 9:00
  • 1
    Your posting to /SaveEmergencyContact/Dhp! Change it to url: '@url.Action("SaveEmergencyContact","Dhp")', assuming you have DhpController Commented Feb 4, 2015 at 9:07
  • 1
    You have completely changed your question with the latest edits making the previous comments and answers meaningless (what has calling those urls got to do with passing multiple parameters from ajax to a controller? You should be asking a new question! But yes, you do need a specific route to make the second example work. Commented Feb 6, 2015 at 1:42

6 Answers 6

30

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This answer is exactly when you need to pass model
It's working fine. for me on: $.ajax({ type: 'POST', url: '/hr/employee/assigncustomer', data: JSON.stringify({ 'employeeCustomerId': contactId, 'customerIds': customerIds }), dataType: 'json', contentType: 'application/json; charset=utf-8', success: function (data) {}}) Thanks
16

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

Comments

3

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

Comments

1

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/

1 Comment

Using stringify did not work passing it to the controller using asp.net mvc4. but passing it without calling stringify did. I noticed stringify works well when the controller param is an object, but not a regular primitive data type.
1
  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })

1 Comment

Please add some explanation to your answer.
0
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";
        }
    });

}

3 Comments

why async: false? This is well known to be a bad practice and it's not necessary in this code at all. Also, answers with explanations tend to be much higher quality.
absolutely correct async not need to write,if you want then use otherwise dont use async ,but i wants to pass 2 parameter in my controller using above code i got success.
Ok but why randomly include something which is bad practice when it's unnecessary for this purpose? Especially since you still haven't added any explanation of what you've done to make the code work compared to what's in the question, someone might think was a necessary part of the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.