0

I am trying to pass Object from Jquery to asp.net mvc controller action. The parameter is always null. what is my mistake?

Creating object for countries

var selectedCountries = [];

var id = 1;

$(".countriesSelection").find('span').each(function() {
  var countryName = $(this).text();
  var profile1 = {};
  profile1.id = id;
  profile1.countryName = countryName;

  selectedCountries.push(profile1)
});

console.log(selectedCountries);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countriesSelection">
  <span>India</span>
  <span>USA</span>
  <span>China</span>
  <span>Japan</span>
</div>

calling controller

selectedCountries = (Object.assign({}, selectedCountries));

            $.ajax({
                url: "AddCountries",
                type: "POST",
                data: { "selectedCountries": selectedCountries },
                traditional: true,
                success: function (result) {
                    console.log(result);
                },
                error: function (err) {
                    console.log("Something went wrong.." + err.status);
                }
            });

    });

Asp.net MVC Controller

  [HttpPost]
 public IActionResult AddCountries(List<ProfileEntity> selectedCountries){
//my c# code comes here but selectedCountries Parameter is always null

}

Profile Entity

public class ProfileEntity
    {
        [Required]
        public string Id { get; set; }

        [Required]
        public string countryName { get; set; }
    }
4
  • 1
    data: JSON.stringify({ "selectedCountries": selectedCountries }), (where selectedCountries is the array) and add contentType: 'application/json' (note traditional: true, only applies to arrays of simple types, not to arrays of complex objects) Commented Apr 19, 2018 at 22:56
  • Object.assign I am trying to convert array to Object Commented Apr 19, 2018 at 23:02
  • You method expects an array of ProfileEntity therefore you need to send it an array, not an object Commented Apr 19, 2018 at 23:05
  • Remove traditional: true, and it works. Commented Apr 20, 2018 at 0:43

1 Answer 1

2

Assuming you have an array like this in selectedCountries variable,

[{
    "id": 1,
    "countryName": "India"
}, {
    "id": 1,
    "countryName": "USA"
}, {
    "id": 1,
    "countryName": "China"
}, {
    "id": 1,
    "countryName": "Japan"
}]

When you execute this line

selectedCountries = (Object.assign({}, selectedCountries));

it will reset the value of selectedCountries to to an object (not an array)

{
    "0": {
        "id": 1,
        "countryName": "India"
    },
    "1": {
        "id": 1,
        "countryName": "USA"
    },
    "2": {
        "id": 1,
        "countryName": "China"
    },
    "3": {
        "id": 1,
        "countryName": "Japan"
    }
}

That does not match with your action method parameter type. For model binding to work, the structure of the data you are sending should match the structure of the parameter type, along with the property names. That means if your server action method expects an array, you should send an array, not an object

You should send the array. Use JSON.stringify to create the json string of the array and send that while specifying your content-type as application/json

This should work. In the below code snippet, i also changed the way you were populating the array using the $.map method (Your current implementation will absolutely work, but i like less code)

var id = 1;

var spans = $("div.countriesSelection").find('span');
var selectedCountries = $.map(spans, function (item)
{
    return { id: id, countryName: $(item).text() };
});

$.ajax({
    url: "AddCountries",
    type: "POST",
    data: JSON.stringify(selectedCountries),
    contentType: "application/json",
    success: function (result)
    {
        console.log('result', result);
    },
    error: function (err)
    {
        console.log("Something went wrong.." + JSON.stringify(err));
    }
});
Sign up to request clarification or add additional context in comments.

11 Comments

what will be datatype for controller parameter?
Same as what you have in the question. It should work public ActionResult AddCountries(List<ProfileEntity> selectedCountries)
Where are you seeing it ?
Are you sure you removed the Object.assign line ? See the working version here jsbin.com/sowubinuwu/edit?html,js,console,output
Switching to map is not necessary. your old code to populate the array will still work.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.