简体   繁体   English

Jquery和Asp.Net MVC通过Jquery Ajax调用将Obejct传递给控制器

[英]Jquery and Asp.Net MVC passing Obejct to Controller through Jquery Ajax call

I am trying to pass Object from Jquery to asp.net mvc controller action. 我试图将对象从Jquery传递到asp.net mvc控制器操作。 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 Asp.net MVC控制器

  [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; }
    }

Assuming you have an array like this in selectedCountries variable, 假设您在selectedCountries变量中有一个像这样的数组,

[{
    "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) 它将selectedCountries的值重置为一个对象 (不是数组)

{
    "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 使用JSON.stringify创建数组的json字符串并将其发送,同时将您的内容类型指定为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) 在下面的代码片段中,我还更改了使用$.map方法填充数组的方式(您当前的实现绝对可以,但是我喜欢更少的代码)

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));
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM