HendPro12
HendPro12

Reputation: 1104

C# Jquery Ajax Post Multiple Data Parameters

In my c# mvc4 application I have three objects I wish to pass to an ActionResult using an AJAX post with Jquery. The objects are two strings and a form collection. Ive had no problems passing only the form collection, but cant seem to get the syntax correct for passing all three. Here is what Ive tried:

 $(document).ready(function () {
        $('#ChangeName').click(function (e) {
            var tdata = $('#form1').serialize();
            var origname = $('#NameDiv').find('input[name="myName"]').first().val();
            var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
            $.ajax({
                type: "POST",
                data: {tdata + origname + newname},
                url: "Home/ChangeName",
                success: function (result) { success(result); }
            });
        });

Ive also tried commas after each variable name in the data: section with and without the brackets. How can I pass all three? When its been successful both string values have populated correctly when debugging but the values dont appear in the ActionResult and show null instead. Ive also tried placing this below data: contentType: "application/x-www-form-urlencoded",

Here is the beginning of my ActionResult as well:

 public ActionResult ChangeName(string Name, string updatedName, FormCollection mCollection)

Upvotes: 0

Views: 13677

Answers (2)

NunoCarmo
NunoCarmo

Reputation: 5509

Can you try:

$(document).ready(function () {
        $('#ChangeName').click(function (e) {
            var tdata = $('#form1').serialize();
            var origname = $('#NameDiv').find('input[name="myName"]').first().val();
            var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
            $.ajax({
                type: "POST",
                data: {
                    mCollection: tdata,
                    Name: origname,
                    updatedName: newname
                },
                url: "Home/ChangeName",
                success: function (result) { success(result); }
            });
        });

Upvotes: 3

Faisal Ahmed
Faisal Ahmed

Reputation: 208

I think the problem is how you are putting the origname and newname in the ajax request. Try this:

var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
     url: 'Home/ChangeName',
     type: "POST",
     data: $("#form1").serialize() + "&origname =" + origname + "&newname =" + newname, 
     success: function (result) { success(result); }
});

Upvotes: 0

Related Questions