从控制器获取数据,以json形式返回并在cshtml中预览

时间:2013-06-24 12:17:35

标签: c# json razor controller

我有一个控制器,我得到结果exam​​pleController.cs:

public expChart{
...
   public ActionResult ByContainer(int id)
    {
        var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds; 

        var kpiElements = CacheService.AllVisibleElements
                                      .Where(x => elementIds.Contains(x.Id)).ToList();

        var container = _kpiContainerService.Find(id);

        var result = _kpiTrendService.MonthByContainer(kpiElements, container);
        return AsJson(result);
    } 
} 

我在example.cshtml中调用它:

<div class="panel" style="display: none;" id="bottom-area-trend-charts" ng-ontroller="exampleController">
    <div >
        TEST
        {{element.Name}}
    </div>

</div>

我认为我的电话有问题。如何在控制器中调用结果?

提前致谢

1 个答案:

答案 0 :(得分:0)

使用类似的东西:

<script type="text/javascript">
    $(function () {
        $.ajax({
            url: "/YourController/ByContainer",
            type: "GET",
            dataType: 'html',
            data: { id: 10 }, // the value id for call your controller
            success: function (data) {
                // make sure your result variable is enumerable.
                $(data).each(function (index, element) {
                    $("#bottom-area-trend-charts div").append("<p>" + element.Name + "</p>");
                });
            },
            error: function (xqr, errorMessage) {
                alert(errorMessage);
            }
        });
    });
</script>

并将您的行动改为:

public JsonResult ByContainer(int id)
{
    var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds; 

    var kpiElements = CacheService.AllVisibleElements
                                    .Where(x => elementIds.Contains(x.Id)).ToList();

    var container = _kpiContainerService.Find(id);

    var result = _kpiTrendService.MonthByContainer(kpiElements, container);

    return Json(result, JsonRequestBehavior.AllowGet);
}