Viewbag没有更新

时间:2015-05-28 11:40:52

标签: c# asp.net ajax asp.net-mvc asp.net-mvc-5

目前在我有一些内联javascript,它对局部视图控制器进行ajax调用,该控制器本应更新viewbag。然而,情况似乎并非如此,数据似乎从主视图中保留为null,因为它从未在那里设置,如果设置了,那么数据仍将保持(测试)。

这是我的javascript ajax调用。

  $.ajax({
            url: btn.data('action-url'),
            data: {
                id: btn.data('id')
            },
            type: 'GET',
            success: function (data) {
                //delete all panels before showing new ones
                $('.panel.panel-default').remove();

                //push the new panels into the view
                //$('#dash-content').html(data);

                //Construct the partial view to be input into the main view

                //Checks to see if browser supports templates
                if ('content' in document.createElement('template')) {

                    var widgetModel = @Html.Raw(Json.Encode(ViewBag.widgets));

                    for (var i = 0; i < widgetModel.length; i++) {
                        var clone = loadwidgets(widgetModel[i]); //This function is in an external js file
                        var inputDestination = document.querySelector('#col2');
                        inputDestination.appendChild(clone);
                        console.log(inputDestination);
                    }
                }

这是它正在调用的Action。

  public ActionResult Dashboard(int? id)
    {
        ModelState.Clear();
        //get all widgets associated dashboard
        var getWidgetsQuery = (from widgets in db.widgets
                               where widgets.DashID == id
                               select widgets);

        ViewBag.widgets = getWidgetsQuery.ToList();


        return PartialView();
    }

1 个答案:

答案 0 :(得分:2)

添加动作以返回数据,即

  public ActionResult DashboardJson(int? id)
    {
        //get all widgets associated dashboard
        var getWidgetsQuery = (from widgets in db.widgets
                               where widgets.DashID == id
                               select widgets);

        var widgets = getWidgetsQuery;

        return Json(widgets, JsonRequestBehavior.AllowGet);
    }

如上所述,在json调用之上声明并序列化您的模型:

var widgetModel = @Html.Raw(Json.Encode(ViewBag.widgets));

然后在您的成功通话中,只需将其重新分配给返回的数据:

widgetModel = data;