0

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 ???

loli pop
  • 75
  • 3
  • 8
  • 1
    `ViewBag` makes no sense. Your `return Json(result, JsonRequestBehavior.AllowGet);` is correct, and then in the success callback your loop through the collection and generate new options(refer [better way to load 2 dropdown in mvc](https://stackoverflow.com/questions/28627421/better-way-to-load-2-dropdown-in-mvc/28640420#28640420) for an example –  Aug 05 '18 at 09:45
  • 1
    Then stop using `VIewBag` altogether, and use a view model and generate the dropdownlist correctly by binding to your view model using `@DropDownListFor(m => m.YourProperty, Model.YourSelectList)` –  Aug 05 '18 at 09:47
  • Ok Thx for the suggestion i will look forward to that, btw do u have any good source of how to use view model? – loli pop Aug 05 '18 at 15:31

1 Answers1

1

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);
}
Akqira
  • 146
  • 1
  • 5