jqGrid不会将JSON数据渲染到网格中

时间:2015-05-11 03:26:35

标签: jquery json jqgrid

尽管我的action方法以JSON格式返回数据,但是jqGrid控件无法呈现它。

以下是以JSON格式返回数据的方法代码。

ContactContext db = new ContactContext();

    //
    // GET: /Contact/

    public JsonResult ContactList(int? selectedContact)
    {

        IQueryable<Contact> contacts = db.Contacts;

        var contactsJson = JsonConvert.SerializeObject(contacts.ToList());

        return Json(contactsJson, JsonRequestBehavior.AllowGet);
    }

Controller类的'ContactList'动作方法返回的数据:

        contactsJson    ""[{\"ContactId\":1,\"FirstName\":\"John\",\"LastName\":\"Doe\",\"EMail\":\"john.doe@gmail.com\",\"Phone\":\"7458593847\",\"BusinessName\":\"microsoft\"},{\"ContactId\":2,\"FirstName\":\"Jack\",\"LastName\":\"Davos\",\"EMail\":\"jack.davos@microsoft.com\",\"Phone\":\"348945485\",\"BusinessName\":\"microsoft\"},{\"ContactId\":3,\"FirstName\":\"Mike\",\"LastName\":\"Strong\",\"EMail\":\"mike.strong@google.com\",\"Phone\":\"950595959\",\"BusinessName\":\"google\"}]"

jqGrid代码:

function populateContactList() {

    $("#ContactTable").jqGrid({
        url: "/Contact/ContactList",
        datatype: "json",
        colNames: ["ID", "First Name", "Last Name", "EMail", "Phone", "Business Name"],
        colModel: [
            { name: "ContactId", index: "ContactId", width: 80 },
            { name: "FirstName", index: "FirstName", width: 200 },
            { name: "LastName", index: "LastName", width: 200 },
            { name: "EMail", index: "EMail", width: 300 },
            { name: "Phone", index: "Phone", width: 100 },
            { name: "BusinessName", index: "BusinessName", width: 200 },
        ],
        //data: result,
        mtype: 'GET',
        autowidth: true, 
        shrinkToFit: false,
        //loadonce: true,
        viewrecords: true,
        gridview: true,
        emptyrecords: "No records to display",
        jsonReader: {
            repeatitems: false,
            //page: function () { return 1; },
            root: function (obj) { return obj; },
            //records: function (obj) { return obj.length; }
        },
        loadComplete: function () {},
        loadError: function (jqXHR, textStatus, errorThrown) {
            alert('HTTP status code: ' + jqXHR.status + '\n' +
                'textstatus: ' + textstatus + '\n' +
                'errorThrown: ' + errorThrown);
            alert('HTTP message body  (jqXHR.responseText: ' + '\n' + jqXHR.responseText);
        }
    });
}

$(document).ready(populateContactList);

1 个答案:

答案 0 :(得分:2)

我认为您的数据已序列化两次,

一行,

var contactsJson = JsonConvert.SerializeObject(contacts.ToList());

,第二次来自JsonResult动作过滤器

return Json(contactsJson, JsonRequestBehavior.AllowGet);

发送json数据,

return Json(contacts.ToList(), JsonRequestBehavior.AllowGet);

而不是

var contactsJson = JsonConvert.SerializeObject(contacts.ToList());

return Json(contactsJson, JsonRequestBehavior.AllowGet);

应该有用。

希望这会有所帮助。