0

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

$('#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

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

[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

    }
Rena
  • 30,832
  • 6
  • 37
  • 72
  • You don't need to manually deserialize the request. If the JSON string actually matches the DTOs you can change the signature to `InsertDesignation(Emp_des_ViewModel emp_desViewModel)`. If it doesn't, manual deserialization won't work either. The code you posted is definitely wrong though. You can't just cast an arbitrary object to a different type. If you used `JsonConvert.DeserializeObject< Emp_des_ViewModel>`(formData)` you'd get the object you want. – Panagiotis Kanavos May 06 '21 at 14:39
  • What does the JSON string look like? – Panagiotis Kanavos May 06 '21 at 14:40

2 Answers2

1

I believe your ajax should look like this

$('#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. I'm not the best person to explain why, so look here for further details. In your controller, you can do this

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.

0

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):

    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:

    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:

    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:

    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:

    [HttpPost]
    public IActionResult InsertDesignation([FromBody]Emp_des_ViewModel formData)
    {
        //other code
        return Json(formData);
    }
    
Rena
  • 30,832
  • 6
  • 37
  • 72