JSON.stringify function does not stringify the grid dataSource correctly

Hi,
I'm trying to send the stringified grid data source to server using ajax. But it seems it doesn't stringify the the datasource correctly. when i run the project it gives bellow error and stringified string is like bellow too. Please help me on this matter.

{"dataSource":{"json":[{"UserKey":1,"UserName":"[email protected]","Email":"[email protected]","EmailConfirmed":true},{"UserKey":2,"UserName":"[email protected]","Email":"[email protected]","EmailConfirmed":true}],"headers":[],"cachingPageSize":0,"dataType":"json","offline":true},"adaptor":{"options":..............


Server Error in '/' Application.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[KalbizCat_OLE.Models.KalbizOLEUserModel]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'dataSource', line 1, position 14.


And my coding is bellow.

Model

  public class KalbizOLEUserModel
    {
        [Required(ErrorMessage = "Key is required")]
        [Column(Order = 0)]
        [Display(Name = "Key")]
        public int UserKey { get; set; }

        [Display(Name = "User Name")]
        public string UserName { get; set; }

        [Display(Name = "Email")]
        public string Email { get; set; }

        [Display(Name = "Email Confirmed")]
        public bool EmailConfirmed { get; set; }

    }


Controller

    public class SystemUsersController : Controller
    {
        string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        [HttpGet]
        public ActionResult Index()
        {
            BuildGrid();
            return View();
        }



        public JsonResult BuildGrid()

        {

            List<KalbizOLEUserModel> SystemUsers = new List<KalbizOLEUserModel>();

            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT UserKey,UserName, Email, EmailConfirmed FROM AspNetUsers ORDER BY UserKey ASC", con))
                {
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {

                            SystemUsers.Add(new KalbizOLEUserModel()
                            {
                                UserKey = Convert.ToInt32(reader.GetValue(0)),
                                UserName = reader.GetString(1),
                                Email = reader.GetString(2),
                                EmailConfirmed = Convert.ToBoolean(reader.GetValue(3)),


                            });


                        }

                            ViewBag.griddata = SystemUsers;
                    }
                }
                con.Close();
            }


             return Json(SystemUsers, JsonRequestBehavior.AllowGet);

           }


        public Object SaveData(string data, Int32 a)
      

        {
            var gridData = JsonConvert.DeserializeObject(data);

            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = null;
            conn = new SqlConnection(conString);
            conn.Open();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_web_SystemUser_Activate";



            IList<KalbizOLEUserModel> UserList = JsonConvert.DeserializeObject<List<KalbizOLEUserModel>>(data);
            for (int i = 0; i < UserList.Count; i++)
            {

                cmd.Parameters.AddWithValue("@UserKey", DbType.Int32).Value = UserList[i].UserKey;
                cmd.Parameters.AddWithValue("@EmailConfirmed", DbType.Boolean).Value = UserList[i].EmailConfirmed;
              
                cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();

            }

            conn.Close();
            return gridData;
        }


    }

View

@{
    ViewBag.Title = "Index";
}

@model KalbizCat_OLE.Models.KalbizOLEUserModel

<script type="text/javascript">


  function btnClick() {


      var obj = $("#FlatGrid").ejGrid("instance");
      obj.batchSave();


      var gridmodel = $("#FlatGrid").ejGrid("model");
      var data = JSON.stringify(gridmodel.dataSource);
      //  alert(data);

      $.ajax({
          url: '/SystemUsers/SaveData',
          type: 'post',
          data: { data: data, a:1 },
          success: function (data) {
              alert('Successfully Saved..!');
          }
      })



    }

</script>



<table style="width:100%">
    <tr>
        <td>
            @Html.EJ().Button("Save").Text("Save").ShowRoundedCorner(true).Size(ButtonSize.Normal).ContentType(ContentType.ImageTextImage).PrefixIcon("e-icon e-save").ClientSideEvents(e => e.Click("btnClick"))
        </td>

        <td align="right"><h2>System Users</h2></td>
    </tr>
    <tr></tr>
</table>

<hr />




@(Html.EJ().Grid<KalbizCat_OLE.Models.KalbizOLEUserModel>("FlatGrid")
        .Datasource(datasource => datasource.Json((IEnumerable<object>)ViewBag.griddata))

        .AllowPaging()
        .PageSettings(Page => Page.PageSize(12))
        .AllowSorting()
        .AllowFiltering()
        .FilterSettings(d => d.FilterType(FilterType.FilterBar))
          .EditSettings(edit => edit.AllowEditing().AllowAdding().EditMode(EditMode.Batch))

        .Columns(col =>
        {

            col.Field(p => p.UserKey).HeaderText("Key").Width(50).IsPrimaryKey(true).AllowEditing(false).TextAlign(TextAlign.Left).Add();
            col.Field(p => p.UserName).HeaderText("User Name").Width(200).AllowEditing(false).TextAlign(TextAlign.Left).Add();
            col.Field(p => p.Email).HeaderText("Email").AllowEditing(false).TextAlign(TextAlign.Left).Add();
            col.Field(p => p.EmailConfirmed).HeaderText("Email Confirmed").TextAlign(TextAlign.Center).EditType(EditingType.BooleanEdit).Add();

        })
)

Thanks.

Kalum




5 Replies

SE Sathyanarayanamoorthy Eswararao Syncfusion Team April 13, 2018 01:06 PM UTC

Hi Kalum, 

Thanks for contacting Syncfusion support. 

We have analyzed your query and the cause of the issue is you are trying to convert Json object into a Collection. So we suggest you to convert the stringified Json object into List object. This query has been explained in the below public forum. Please refer the below link for more details. 


Regards, 
Sathyanarayanamoorthy 




KA kalum April 13, 2018 05:07 PM UTC

Hi Sathyanarayanamoorthy,

Thank you very much for your reply. But my problem begins at "var data = JSON.stringify(gridmodel.dataSource);"   of "btnClick()" function. It stringify the datasource including it's  adaptor, options and some more. I think that is why it cannot be Deserialize in the server. the stringified string is like bellow. I don't understand why ejgrid datasource stringify like this. In my other solutions same thing works fine and stringify without unwanted things.


Stringified Datasource

{"dataSource":{"json":[{"UserKey":1,"UserName":"[email protected]","Email":"[email protected]","EmailConfirmed":true},{"UserKey":2,"UserName":"[email protected]","Email":"[email protected]","EmailConfirmed":false}],"headers":[],"cachingPageSize":0,"dataType":"json","offline":true},"adaptor":{"options":{"from":"table","requestType":"json","sortBy":"sorted","select":"select","skip":"skip","group":"group","take":"take","search":"search","count":"requiresCounts","where":"where","aggregates":"aggregates","antiForgery":"antiForgery"},"pvt":{}}}


function btnClick() {
      var obj = $("#FlatGrid").ejGrid("instance");
      obj.batchSave();
      var gridmodel = $("#FlatGrid").ejGrid("model");

      var data = JSON.stringify(gridmodel.dataSource);

      //  alert(data);
      $.ajax({
          url: '/SystemUsers/SaveData',
          type: 'post',
          data: { data: data, a:1 },
          success: function (data) {
              alert('Successfully Saved..!');
          }
      })
    }

Thanking you very much if you can explain me the exact fault.
Regards
Kalum



SE Sathyanarayanamoorthy Eswararao Syncfusion Team April 16, 2018 01:16 PM UTC

Hi Kalum, 

We have analyzed your query and the mentioned adaptor details are added to the dataSource because you have defined the dataSource for the grid as ds.JSON(IEnumerable object). So, this will be considered as JSON adaptor by default, the adaptor details are added to the dataSource of the grid. So, we suggest you to use IEnumerable object as dataSource for the grid. 

 Refer the below code example. 

     
@(Html.EJ().Grid<object>("FlatGrid") 
             .Datasource((IEnumerable<object>)ViewBag.dataSource) 
             .AllowPaging() 
                    .PageSettings(paging => paging.PageSize(3)) 
                    .AllowFiltering() 
                    .AllowSorting() 
                    
                                 ... 
 


If you need any further assistance please get back to us. 

Regards, 
Sathyanarayanamoorthy


KA kalum April 17, 2018 03:48 PM UTC

Hi,
Now it works fine. Thank you very much for your kind help.
Regards
Kalum


SE Sathyanarayanamoorthy Eswararao Syncfusion Team April 18, 2018 10:58 AM UTC

Hi Kalum, 

We are happy to hear that your issue has been resolved. 
If you need any further assistance please get back to us. 

Regards, 
Sathyanarayanamoorthy 


Loader.
Up arrow icon