简体   繁体   中英

DataTable to JSON to Controller to jqGrid

I have 3 forms, Associate.cs, HomeController.cs, Index.cshtml.

I load a DataTable from Associate.cs and use this code to get it into JSON format.

    public string GetAssociateFromDB()
       //code omitted
                var json = JsonConvert.SerializeObject(dt, Formatting.Indented);
                jsonData = json;
            }               
        }
        return jsonData; //return is good

I call this from HomeController.cs .

    public JsonResult GetJsonData()
    {
        Associate associate = new Associate();
        string jsonData = associate.GetAssociateFromDB();
        System.Diagnostics.Debug.WriteLine(jsonData); //for testing purposes
        return Json(jsonData, JsonRequestBehavior.AllowGet);  //need to pass to `Index.cshtml`
    }

However, this code doesn't get hit unless I put the method in this block:

    [HttpGet]
    public ActionResult Index()
    {
        GetJsonData(); //if not called here, it never gets hit.

        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

        return View();
    }

Then, I try to pass it to Index.cshtml, via $.getJSON method, but it never reaches it.

    jQuery(document).ready(function () {
        var mydata;
     $.getJSON('@Url.Action("HomeController", "GetJsonData")', function(data) {
         datatype: 'json'
         mydata = data;
         console.log(data); //unsure if this works or not.
     });

I am then trying to supply that data for a jqGrid (this is just under the above code):

 $("#grid").jqGrid({
    data: mydata,
    datatype: "json",
    width: '100%',
    colNames: ["Seq ID", "Fund ID", "Name", "Fund", "Bonus", "Allocation", "Blank", "Begin", "End"],
    colModel: [{
        name: 'seqid',
        index: 'seqid',
        editable: true,
    },....//Code omitted

I can't seem to get the data from the Controller to Index.cshtml . I have read on a blog that there is a problem with cache in IE 8, which is what I am testing in, but I'm pretty sure that's not my initial problem.

I've read the jQGrid documentation and searched many times, but the only example is for this kind of thing is for PHP or in a different context. I tried putting [HttpGet] above the GetJsonData method, and that did not work either.

It's also important to note I haven't written much(any) jQuery before.

Try this below code.

Url.Action('actionname','controllername')

javascript:

  $(document).ready(function () {
            var mydata;
         $.getJSON('@Url.Action("GetJsonData", "Home")', function(data) {
             datatype: 'json'
             mydata = data;
             gridFn(data);
         });

function gridFn(data)
{
//here grid code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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