简体   繁体   English

将列表的 JSON 字符串反序列化为 c# object

[英]Deserialize JSON string for list to c# object

I am working with .netcore asp.net project using C# jquery ajax json, I passed model from ajax call and received data(formdata) in string format but not be able to convert data of EmployeesList from string object to list object. I am working with .netcore asp.net project using C# jquery ajax json, I passed model from ajax call and received data(formdata) in string format but not be able to convert data of EmployeesList from string object to list object.

ajax code ajax代码

$('#bttn_Click').click(function () {
                debugger;                
                var empListVal = null;
                empListVal = [];
                $('input:checkbox:checked').each(function () {
                    empListVal .push($(this).attr('value'));
                });
                var Emp_des_ViewModel = {
                    Designation: des_Value,
                    Department: dep_Value,                    
                    EmployeesList: empListVal 
                };                
                $.ajax({
                    type: "post",                    
                    data: "formData=" + JSON.stringify(Emp_des_ViewModel),
                    url: '/Emp_Designation_Assign/InsertDesignation',
                    datatype: "json",
                    success: function (result) {
                        alert(result);
                        window.location.href = "/Emp_Designation_Assign/InsertDesignation";
                        console.log(result);
                    }
                });
            });

Emp_des_ViewModel.cs Emp_des_ViewModel.cs

public class Emp_des_ViewModel 
    {
        public string Designation{ get; set; }
        public string Department{ get; set; }
        public List<SelectListItem> EmployeesList{ get; set; }
    }

Emp_Designation_AssignController.cs Emp_Designation_AssignController.cs

[HttpPost]
    public IActionResult InsertDesignation(string formData)
    {
       var formdata = JsonConvert.DeserializeObject(formData);
       Emp_des_ViewModel emp_desViewModel = new Emp_des_ViewModel();
       emp_desViewModel = (Emp_des_ViewModel)formdata;
       //other code

    }

I believe your ajax should look like this我相信你的 ajax 应该是这样的

$('#bttn_Click').click(function () {
            debugger;                
            var empListVal = null;
            empListVal = [];
            $('input:checkbox:checked').each(function () {
                empListVal .push($(this).attr('value'));
            });
            var Emp_des_ViewModel = {
                Designation: des_Value,
                Department: dep_Value,                    
                EmployeesList: empListVal 
            };                
            $.ajax({
                type: "post",           
                contentType: 'application/json',         
                data: JSON.stringify(Emp_des_ViewModel),
                url: '/Emp_Designation_Assign/InsertDesignation'
                }).done(function (result) {
                    alert(result);
                    window.location.href = "/Emp_Designation_Assign/InsertDesignation";
                    console.log(result);
            });
        });

Avoid using success and use .done() instead.避免使用success并改用.done() I'm not the best person to explain why, so look here for further details.我不是解释原因的最佳人选,因此请在此处查看更多详细信息。 In your controller, you can do this在您的 controller 中,您可以执行此操作

public IActionResult InsertDesignation([FromBody]Emp_des_ViewModel formData)
{
   Emp_des_ViewModel emp_desViewModel = formdata;
   //other code
}

.Net will handle deserializing automatically for you, if JSON is compatible with your model.如果 JSON 与您的 model 兼容,.Net 将为您自动处理反序列化。

You have some mistakes here:你这里有一些错误:

  1. The correct way to deserialize the json string to model should be(BTW, As other communities said, no need deserialize the json manually , just send model and the default model binding system will help you deserialize to model): The correct way to deserialize the json string to model should be(BTW, As other communities said, no need deserialize the json manually , just send model and the default model binding system will help you deserialize to model):

     var formdata = JsonConvert.DeserializeObject<Emp_des_ViewModel>(formData);
  2. EmployeesList in your model is type of List<SelectListItem> , you could check the source code of SelectListItem below, it contains Disabled , Group , Selected , Text and Value properties:您的 model 中的EmployeesListList<SelectListItem>的类型,您可以查看下面SelectListItem的源代码,它包含DisabledGroupSelectedTextValue属性:

     public class SelectListItem { public SelectListItem(); public SelectListItem(string text, string value, bool selected); public SelectListItem(string text, string value, bool selected, bool disabled); public bool Disabled { get; set; } public SelectListGroup Group { get; set; } public bool Selected { get; set; } public string Value { get; set; } }

    So you need send the data like below:因此,您需要发送如下数据:

     empListVal.push({ "PropertyName": "CheckedValue1" }, {"PropertyName":"CheckedValue2"});

    In your code it may should be:在您的代码中,它可能应该是:

     empListVal.push({ "PropertyName":$(this).attr('value')});
  3. If you must insist on sending json( empListVal.push($(this).attr('value')); ) in your past way, you need change your model:如果您必须坚持以过去的方式发送 json( empListVal.push($(this).attr('value')); ),则需要更改 model:

     public class Emp_des_ViewModel { public string Designation { get; set; } public string Department { get; set; } public List<string> EmployeesList { get; set; } }

A whole working demo you could follow:您可以遵循的完整工作演示

  1. Model: Model:

     public class Emp_des_ViewModel { public string Designation { get; set; } public string Department { get; set; } public List<SelectListItem> EmployeesList { get; set; } }
  2. View:看法:

     <button type="button" id="bttn_Click">click</button> @section Scripts { <script> $('#bttn_Click').click(function () { debugger; var empListVal = null; empListVal = []; empListVal.push({ "Value": "emp1" }, { "Value": "emp2" }); var Emp_des_ViewModel = { Designation: "aaa", Department: "bbb", EmployeesList: empListVal }; $.ajax({ type: "post", contentType: 'application/json', data: JSON.stringify(Emp_des_ViewModel), url: '/Emp_Designation_Assign/InsertDesignation', datatype: "json", success: function (result) { //... } }); }); </script> }
  3. Controller: Controller:

     [HttpPost] public IActionResult InsertDesignation([FromBody]Emp_des_ViewModel formData) { //other code return Json(formData); }

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

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