locked
call of a JsonResult from javascript is not working ? Please help RRS feed

  • Question

  • User-1355965324 posted

    I am calling a jason result for  the multiple selection of  Menu Names as a treeview, But the the function is not calling 

    My Homecotroller code 

    [HttpPost]
            public JsonResult GetMenuList()
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("MenuID");
                dt.Columns.Add("ParentID");
                dt.Columns.Add("MenuName");
    
                dt.Rows.Add(1, 0, "Customer");
                dt.Rows.Add(2, 0, "Supplier");
                dt.Rows.Add(3, 1, "Add Customer");
                dt.Rows.Add(4, 1, "Edit Customer");
                dt.Rows.Add(5, 2, "Add Supplier");
                dt.Rows.Add(6, 2, "Edit Supplier");
                String jsonResult = JsonConvert.SerializeObject(dt);
                return Json(jsonResult);
            }

    In cshtmlfile

    <link href="~/css/bootstrap.min.css" rel="stylesheet" >
    <script src="~/js/jquery.min.js"></script>
    <script src="~/js/bootstrap.min.js"></script>
    <link href="~/css/jquery.bootstrap.treeselect.css" rel="stylesheet" >
    <script src="~/js/jquery.bootstrap.treeselect.js"></script>
    <div class="controls col-sm-9"> <select multiple="multiple" id="main_menu" name="main_menu" onchange="FillMenuList()"></select> </div> function FillMenuList() { $.ajax({ type: "POST", url: "Home/GetMenuList", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { //alert(data.d); //dynamically generate options and populate <select> $(JSON.parse(data.d)).each(function (index, item) { var option = ""; if (parseInt(item.ParentID) > 0) { option = '<option value="' + item.MenuID + '" data-parent="' + item.ParentID + '">' + item.MenuName + '</option>'; } else { option = '<option value="' + item.MenuID + '">' + item.MenuName + '</option>'; } $("#main_menu").append(option); }); $('#main_menu').treeselect(); } }); }

    Regards

    Pol

    Wednesday, February 13, 2019 10:10 AM

Answers

  • User839733648 posted

    Hi polachan,

    Your Json result occurs may be because of the version of Newtonsoft.Json you've installed.

    I suggest that you could check if it is the latest one. 

    When you use Datatable you may meet the issue, and a good work around is that you use an array instead of a datatable.

    You could modify your controller like below:

            public class MenuInfo
            {
                public int MenuID { get; set; }
                public int ParentID { get; set; }
                public string MenuName { get; set; }
            }
            [HttpPost]
            public JsonResult GetMenuList()
            {
                List<MenuInfo> menulist = new List<MenuInfo>();
                menulist.Add(new MenuInfo { MenuID = 1, ParentID = 0, MenuName = "Customer" });
                menulist.Add(new MenuInfo { MenuID = 2, ParentID = 0, MenuName = "Supplier" });
                menulist.Add(new MenuInfo { MenuID = 3, ParentID = 1, MenuName = "Add Customer" });
                menulist.Add(new MenuInfo { MenuID = 4, ParentID = 1, MenuName = "Edit Customer" });
                menulist.Add(new MenuInfo { MenuID = 5, ParentID = 2, MenuName = "Add Supplier" });
                menulist.Add(new MenuInfo { MenuID = 6, ParentID = 2, MenuName = "Edit Supplier" });
                String jsonResult = JsonConvert.SerializeObject(menulist);
                return Json(jsonResult);
            }

    Best Reagrds,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 15, 2019 7:09 AM

All replies

  • User839733648 posted

    Hi polachan,

    You controller code is ok and the key point is the code in your view.

    You should pay attention that the data passing from the controller is already json data.

    You could console it to see, so you do not have to write like data.d to get the data.

    I suggest that you do not have to write as a FillMenuList function and set the onchange event.

    You could just write it when page is loading and you could write the cshtmlfile like:

    @section scripts
    {
        <script src="~/Content/jquery.bootstrap.treeselect.js"></script>
        <link href="~/Content/jquery.bootstrap.treeselect.css" rel="stylesheet" />
        <div class="controls col-sm-9">
            <select multiple="multiple" id="main_menu" name="main_menu"></select>
        </div>
        <script>
            $(function () {
                $.ajax({
                    type: "POST",
                    url: "/Home/GetMenuList",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        $.each(JSON.parse(data), function (index, item) {
                            var option = "";
                            if (parseInt(item.ParentID) > 0) {
                                option = '<option value="' + item.MenuID + '" data-parent="' + item.ParentID + '">' + item.MenuName + '</option>';
                            } else {
                                option = '<option value="' + item.MenuID + '">' + item.MenuName + '</option>';
                            }
    
                            $("#main_menu").append(option);
                        });
                        $('#main_menu').treeselect();
    
                    }
                });
            })
        </script>
    }

    result:

    Best Regards,

    Jenifer

    Thursday, February 14, 2019 6:01 AM
  • User-1355965324 posted

    Many Many Thanks Jeni 

    I applied your code but  now the  record is not coming from the data table  in home controller to the view. The treeview just shows like Undefined>  I have given the link on google drive to see the result how it comes on the view. When the page load it going to the data table but the jason result is not coming to the view.  The data table is not fetching the data proper way. The Json result variable shows the its value as given below. So when it comes to view it shows as undefined

    {"DataTable.RemotingVersion":{"Major":2,"Minor":0,"Build":-1,"Revision":-1,"MajorRevision":-1,"MinorRevision":-1},"XmlSchema":"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<xs:schema xmlns=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">\r\n  <xs:element name=\"Table1\">\r\n    <xs:complexType>\r\n      <xs:sequence>\r\n        <xs:element name=\"MenuID\" type=\"xs:string\" msdata:targetNamespace=\"\" minOccurs=\"0\" />\r\n        <xs:element name=\"ParentID\" type=\"xs:string\" msdata:targetNamespace=\"\" minOccurs=\"0\" />\r\n        <xs:element name=\"MenuName\" type=\"xs:string\" msdata:targetNamespace=\"\" minOccurs=\"0\" />\r\n      </xs:sequence>\r\n    </xs:complexType>\r\n  </xs:element>\r\n  <xs:element name=\"tmpDataSet\" msdata:IsDataSet=\"true\" msdata:MainDataTable=\"Table1\" msdata:UseCurrentLocale=\"true\">\r\n    <xs:complexType>\r\n      <xs:choice minOccurs=\"0\" maxOccurs=\"unbounded\" />\r\n    </xs:complexType>\r\n  </xs:element>\r\n</xs:schema>","XmlDiffGram":"<diffgr:diffgram xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:diffgr=\"urn:schemas-microsoft-com:xml-diffgram-v1\">\r\n  <tmpDataSet>\r\n    <Table1 diffgr:id=\"Table11\" msdata:rowOrder=\"0\" diffgr:hasChanges=\"inserted\">\r\n      <MenuID>1</MenuID>\r\n      <ParentID>0</ParentID>\r\n      <MenuName>Customer</MenuName>\r\n    </Table1>\r\n    <Table1 diffgr:id=\"Table12\" msdata:rowOrder=\"1\" diffgr:hasChanges=\"inserted\">\r\n      <MenuID>2</MenuID>\r\n      <ParentID>0</ParentID>\r\n      <MenuName>Supplier</MenuName>\r\n    </Table1>\r\n    <Table1 diffgr:id=\"Table13\" msdata:rowOrder=\"2\" diffgr:hasChanges=\"inserted\">\r\n      <MenuID>3</MenuID>\r\n      <ParentID>1</ParentID>\r\n      <MenuName>Add Customer</MenuName>\r\n    </Table1>\r\n    <Table1 diffgr:id=\"Table14\" msdata:rowOrder=\"3\" diffgr:hasChanges=\"inserted\">\r\n      <MenuID>4</MenuID>\r\n      <ParentID>1</ParentID>\r\n      <MenuName>Edit Customer</MenuName>\r\n    </Table1>\r\n    <Table1 diffgr:id=\"Table15\" msdata:rowOrder=\"4\" diffgr:hasChanges=\"inserted\">\r\n      <MenuID>5</MenuID>\r\n      <ParentID>2</ParentID>\r\n      <MenuName>Add Supplier</MenuName>\r\n    </Table1>\r\n    <Table1 diffgr:id=\"Table16\" msdata:rowOrder=\"5\" diffgr:hasChanges=\"inserted\">\r\n      <MenuID>6</MenuID>\r\n      <ParentID>2</ParentID>\r\n      <MenuName>Edit Supplier</MenuName>\r\n    </Table1>\r\n  </tmpDataSet>\r\n</diffgr:diffgram>"}

    The view file image

    https://drive.google.com/open?id=19HIzqcoxYHNiIPb8DxHwyOnw5d9fiiyb

    Please can you help me

    WIth Many Thanks

    Pol

    Thursday, February 14, 2019 7:14 AM
  • User-474980206 posted

    you have a couple issues

    1) a standard JsonConvert of a dataset, the data is actually an xml string (XmlDiffGram property). You need to use the DataTableConverter class instead:

      https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Converters_DataTableConverter.htm

    2) return Json() expects an object it converted to Json, so when you pass it a string it makes it a string. the client would need to convert twice. to return an object you have already converted to a Json string its:

       return Content(jsonString, "application/json");

    note: not sure why you are not using poco objects instead of a DataTable.

    Thursday, February 14, 2019 4:12 PM
  • User-1355965324 posted

    Bruce

    Please can you advise me  how to bring the data  using poco objects . Please can you give me the code using my example . I dont want to use datatable . Please help

    Thursday, February 14, 2019 4:53 PM
  • User839733648 posted

    Hi polachan,

    Your Json result occurs may be because of the version of Newtonsoft.Json you've installed.

    I suggest that you could check if it is the latest one. 

    When you use Datatable you may meet the issue, and a good work around is that you use an array instead of a datatable.

    You could modify your controller like below:

            public class MenuInfo
            {
                public int MenuID { get; set; }
                public int ParentID { get; set; }
                public string MenuName { get; set; }
            }
            [HttpPost]
            public JsonResult GetMenuList()
            {
                List<MenuInfo> menulist = new List<MenuInfo>();
                menulist.Add(new MenuInfo { MenuID = 1, ParentID = 0, MenuName = "Customer" });
                menulist.Add(new MenuInfo { MenuID = 2, ParentID = 0, MenuName = "Supplier" });
                menulist.Add(new MenuInfo { MenuID = 3, ParentID = 1, MenuName = "Add Customer" });
                menulist.Add(new MenuInfo { MenuID = 4, ParentID = 1, MenuName = "Edit Customer" });
                menulist.Add(new MenuInfo { MenuID = 5, ParentID = 2, MenuName = "Add Supplier" });
                menulist.Add(new MenuInfo { MenuID = 6, ParentID = 2, MenuName = "Edit Supplier" });
                String jsonResult = JsonConvert.SerializeObject(menulist);
                return Json(jsonResult);
            }

    Best Reagrds,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 15, 2019 7:09 AM
  • User-1355965324 posted

    Many Many Thanks Jeni. It is working fine and Many thanks for the support

    Friday, February 15, 2019 9:00 AM