-2

I am using aspnet MVC 5 in Visual Studio 2014.1 I have a combobox that is filled with data from the database:

ViewBag.Brans = new SelectList(db.Brans.OrderBy(m => m.Ad), "No", "Ad");
@Html.DropDownList("Brans", null, htmlAttributes: new { @class = "form-control" })

Then i have another combobox. and i want to fill that combobox after i select an option from first combo. Its like selecting country from the first combo. then cities will appear in the second one.

Does any of you know how to do this?

2

3 Answers 3

2

One of the options is to to make Ajax request to action which will return your list items

  public virtual JsonResult GetCountryStates()
        {
            return Json(
                new
                {
                    new List<SelectListItem>() {YOUR ITEMS HERE}
                });
        }

Then in your Ajax callback body put code like that

function (data) {
                //var selValue;

                data = $.map(data, function (item, a) {
                    if (item.Selected) {
                        selValue = item.Value;
                    }
                    return "<option value=\"" + item.Value + "\" " + (item.Selected ? "selected" : "") + ">" + item.Text + "</option>";
                });
                $('statesSelect').html(data.join(""));
                $('statesSelect').val(selValue);
            },
Sign up to request clarification or add additional context in comments.

Comments

0

@fly_ua : Good way of populating depending dropdown But what if we post form and on selected value we fetch next dropdown data from our controller and again reload the form? This might be the secure way rather than doing AJAX call.

1 Comment

Hi Kishan, Possibly yes, but in my case you are already authenticated in members section and all Actions in MVC contains [Authoroze] and Role check. So as i wrote - this is only one of the possible ways.
0
$('#@Html.Encode(Html.IdFor(x => x.YourProperty))')on("Change", function (event) {
    event.preventDefault();
    var id = $(this).val();

    $.ajax({
        url: '@Url.Action("ActionName", "ControllerName")',
        type: "GET",
        data: {
            id: id,
        },
        success: function (result) {
            $('#@Html.Encode(Html.IdFor(x => x.SecondDropDownProperty))').html(result)
        }
    });
});

create one view with dropdown and rendor razor JSON with this view

By doing this you will create generic dependent dropdown list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.