如何使用jQuery ajax调用将数据转换为MVC 5 app中的Json?

时间:2017-11-10 09:02:51

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

代码如下:

1)实体类:

public partial class EnergeticalComplex : TrackableBaseObject, IWithDbAffiliateFieldBlockField
{
    private ICollection<Cell> _cells;
    private ICollection<Document> _documents;

    public int? AffiliateId { get; set; }
    public virtual Affiliate Affiliate { get; set; }

    public int? FieldBlockId { get; set; }
    [AutoQueryRoot]
    public virtual FieldBlock FieldBlock { get; set; }

    public int? FieldId { get; set; }
    [AutoQueryRoot]
    public virtual Field Field { get; set; }

    [NotNull]
    [AutoQueryRoot]
    public virtual ICollection<Cell> Cells
    {
        get { return _cells ?? (_cells = new List<Cell>().WithLock(SyncRoot)); }
    }

    [NotNull]
    [TrackableRelation]
    public virtual ICollection<Document> Documents
    {
        get { return _documents ?? (_documents = new List<Document>().WithLock(SyncRoot)); }
    }
}

2)在控制器中:

public JsonResult ComboBoxBalanse(int fieldId)
{
    List<EnergeticalComplex> eComplex;
    using (var c = _contextFactory.CreateContext())
    {
        var eComplexesSet = c.Set(c.GetType()
            .EntityTypes()
            .First(t => typeof(IEnergeticalComplex).IsAssignableFrom(t)));
        eComplex = eComplexesSet
            .Cast<EnergeticalComplex>()
            .Where(ec => ec.Field.Id == fieldId && !ec.Name.Contains("KTP"))
            .ToList();
    }

    ViewData["EnergeticalComplexList"] = eComplex;
    ViewData["fieldId"] = fieldId;

    return Json(eComplex, JsonRequestBehavior.AllowGet);
}

3)在JavaScript模块中:

function onClickShowButton() {
    var selectBoxField = $("#divFieldsComboBox").dxSelectBox("instance");
    var indField = selectBoxField.option("value");

    $.ajax({
        contentType: "application/json; charset=utf-8",
        type: 'POST',
        url: '/LostEnergyCalculation/ComboBoxBalanse',
        dataType: 'json',
        data: "{ fieldId: " + indField + " }"
    }).done(function (data) {
        alert(JSON.stringify(data));
    });
}

程序流程在.done()之后不会进入块。

1 个答案:

答案 0 :(得分:1)

看起来你正在使用具有更多类成员变量的实体类! 在这种情况下,由于'eComplex'对象中的循环引用,可能存在JSon序列化问题。 为了防止这种情况,在没有所有子类成员变量的情况下声明新类,或者使用condition_a(1)仅使用必需元素。 即在你的控制器

__call__