Search code examples
javascriptjqueryajaxasp.net-mvchtml-helper

Is there a way to return Json With ViewBag


Following code, is to populate IntakeName to a Html Helper DropDownlist

Controller Code :

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

        return View();
    }

View Code :

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

By default / During PageLoad the DropDownList inside a div id='HiddenIntake' is hide using jquery. After a textbox id='UserID' is fill with value then I pass this value to controller and update the Intake DropDownList and show back using jquery as below :

Jquery Ajax Code :

$(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();
            }
});

Controller Code :

    [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);
    }

As you can see the ViewBag is to update the Intake DropDownList but the problem is the controller is not returning View so that ViewBag doesnt work. And if is returning View, then ajax won't fall into success function.

Is there anyway to make the ViewBag work and fall into success function in ajax ???


Solution

  • You can use only ajax and Javascript to populate your dropdown as following.

    1. Controller side

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

    2. View side : 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. Controller POST method

    [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);
    }