有没有办法 return Json With ViewBag

Is there a way to return Json With ViewBag

以下代码,是将 IntakeName 填充到 Html Helper DropDownlist

控制器代码:

    public ActionResult Index()
    {
        ViewBag.intake = new SelectList(db.Intakes, "IntakeID", "IntakeName");

        return View();
    }

查看代码:

@Html.DropDownList("intake", null, htmlAttributes: new { @class = "form-control" })

默认情况下/在 PageLoad 期间,div id='HiddenIntake' 中的 DropDownList 使用 jquery 隐藏。在文本框 id='UserID' 填充值后,我将此值传递给控制器​​并更新 Intake DropDownList 并使用 jquery 显示回来,如下所示:

Jquery Ajax 代码:

$(document).ready(function(){

var x = $('#UserID').val();

            if (x.length > 0) {

                $.ajax({
                    type: "POST",
                    url: "/Payment/IntakeDropDownList",
                    data: { 'values': x },
                    success: function () {
                        $('#HiddenIntake').show();
                    },
                    error: function () {
                        alert('Failed');
                    }
                });

            } else {
                $('#HiddenIntake').hide();
            }
});

控制器代码:

    [HttpPost]
    public ActionResult IntakeDropDownList(int values)
    {
        var result = (from t in db.EnrollmentDetails
                      join i in db.Intakes on t.IntakeID equals i.IntakeID
                      where t.UserID == values
                      select new { i.IntakeID, i.IntakeName }).ToList();


        ViewBag.intake = new SelectList(result, "IntakeID", "IntakeName");

        return Json(result, JsonRequestBehavior.AllowGet);
    }

如您所见,ViewBag 将更新 Intake DropDownList,但问题是控制器未返回 View,因此 ViewBag 无法正常工作。而如果是返回View,那么ajax就不会落入success函数。

在ajax中有没有办法让ViewBag工作并进入success函数???

您只能使用 ajax 和 Javascript 来填充您的下拉列表,如下所示。

1.控制器端

 public ActionResult Index()
{
    // remove this line
    // ViewBag.intake = new SelectList(db.Intakes, "IntakeID", "IntakeName");

    return View();
}

2。视图侧:AJAX

var x = $('#UserID').val();

        if (x.length > 0) {

            $.ajax({
                type: "POST",
                url: "/Payment/PopulateIntakeDropDown",
                data: { 'values': x },
                success: function (data) {
                   // test some stuff here to see if there is no errors 
                   // and at least an element in data
                   // then build your dropdown using javascript as following
                   // and i assume that you have an <select> element generated
                   // by your @Html.DropdownList helper with Id : intake   
                   // so after all that, you can loop inside data (returned from controller)
                   // and for each element inside we will create an <option value=""></option> 
                   // and do not forget to clear all "option" tags before populating 
                    $('#intake option').remove()
                    $.each(data, function(index,elementIntake){                          
                    $('#intake').append('<option value="' + elementIntake.IntakeID + '">' + elementIntake.IntakeName + '</option>')   
                       })


                },
                error: function () {
                    alert('Failed');
                }
            });

        } else {
            // depends of your personal choice of UI behavior, keep or remove
            // $('#HiddenIntake').hide();
        }
     });

3。控制器POST方法

[HttpPost]
public ActionResult PopulateIntakeDropDown(int values)
{
    var result = (from t in db.EnrollmentDetails
                  join i in db.Intakes on t.IntakeID equals i.IntakeID
                  where t.UserID == values
                  select new { i.IntakeID, i.IntakeName }).ToList();

    // remove this line
    // ViewBag.intake = new SelectList(result, "IntakeID", "IntakeName");

    return Json(result, JsonRequestBehavior.AllowGet);
}