有没有办法用ViewBag返回Json

时间:2018-08-05 09:41:33

标签: javascript jquery ajax asp.net-mvc html-helper

以下代码是将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期间,使用jQuery隐藏div id ='HiddenIntake'内的DropDownList。在用值填充文本框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不会进入成功功能。

无论如何,有没有办法使ViewBag正常工作并在Ajax中发挥成功的作用?

1 个答案:

答案 0 :(得分:0)

您只能使用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);
}