在AJAX响应中读取MVC模型

时间:2016-04-24 10:57:30

标签: jquery ajax asp.net-mvc asp.net-ajax

我发送一个请求来获取GeneralDictViewmodel对象及其字典,但它只获取自身,而不是它在AJAX响应中的字典。我该如何解决这个问题?

    $.ajax({
        url: getAllGeneralDictUrl,
        type: 'POST',
        cache: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data, status, resObject) {
            alert("success..." + data); 

        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });


    public JsonResult GetAllGeneralDict()
    { 
            GeneralDictServiceClient generalDictSvc = new GeneralDictServiceClient();
            GeneralDictViewModel generalDictRes = new GeneralDictViewModel();
            generalDictRes.ShipTypes = generalDictSvc.GetGeneralDict("SHIP_TYPE").ToDictionary(x => x.KEY_ITEM, x => x.VALUE_ITEM);
            generalDictRes.BodyMaterials = generalDictSvc.GetGeneralDict("BODY_MATERIAL").ToDictionary(x => x.KEY_ITEM, x => x.VALUE_ITEM);
            generalDictRes.Designations = generalDictSvc.GetGeneralDict("DESIGNATION").ToDictionary(x => x.KEY_ITEM, x => x.VALUE_ITEM);
             return Json(generalDictRes);
    }

1 个答案:

答案 0 :(得分:0)

首先,如果你要提取数据,你应该在你的ajax调用中“获取”。

try {
    $.ajax({
        url: 'template/GetAllGeneralDict',
        type: 'POST',
        cache: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data, status, resObject) {
            alert("success..." + data);

        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });
} catch (e) {
    window.location.href = SiteRootPath + "default.aspx";
    $('#loading').hide();
}

第二:您应该在Controller的返回函数中使用JSON数据编写JsonRequestBehavior.AllowGet

public JsonResult GetAllGeneralDict()
        {
            var abcObj = new Animal() { Id = 1, Name = "ZTom" };

            return Json(abcObj, JsonRequestBehavior.AllowGet);
        }