How to pass the list of objects from view to MVC controller using json.stringify

前端 未结 2 1132
谎友^
谎友^ 2021-01-22 00:16

I have tried with following code but shows null in the controller side..

view:



        
相关标签:
2条回答
  • 2021-01-22 00:53

    There is problem with data that you are sending to server. you don't need to JSON.stringify 2 times.

     function getme() {
        debugger;
        var emp = [
        { empid: 1, name: 'sasi' },
        { empid: 2, name: 'sathish' }
        ];
        emp = JSON.stringify({ emp: emp });//make json string once 
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/Home/getemplist',
            data: emp //send it to server
        });
     }
    
    0 讨论(0)
  • 2021-01-22 01:01

    After a lot of searches in google.. I found the way to post the list of objects to controller.. i have modified little bit in my code... here it is!!

    script :

    var emp = [{ 'empid': 1, 'name': 'sasi' },{ 'empid': 2, 'name': 'sathish'}];
        emp = JSON.stringify(emp)
        $.post("/Home/getemplist/", { 'emp': emp }) 
    

    Controller:

    Here i just changed the parameter to string type. using JavaScriptSerializer you can able to convert this string data to your class list objects.. you can understand it better if u see my code below:

      public void getemplist(string emp) 
        {
            List<Emp> personData;
            JavaScriptSerializer jss = new JavaScriptSerializer();
            personData = jss.Deserialize<List<Emp>>(emp);
            // DO YOUR OPERATION ON LIST OBJECT
    
        }
    

    Include this (System.Web.Script.Serialization) namespace in your controller inorder to use the JavaScriptSerializer class.

    Hope this helps !! Happy coding :)

    0 讨论(0)
提交回复
热议问题