2

I would like to have small example screen which should have two combo. First one should display the name of the countries from country table and upon selecting the country name in the combo, next combo should be displayed with the district name.

Country Table structure:

Country Name,
Country Id

District table structure.

District id
Country id
District name

Anybody can help me?

1

2 Answers 2

5

it's kinda easy...

the 1st dropdown is easy, just pass the IEnumerable in the model and voilá.

the 2nd dropdown is as easy but just takes a little bit more code:

all you need to do is to call a method and send the value of the first dropdown, then in your method, just call the DB and return a JsonResult

example:

<select id="dropdown1">
    <option value="" selected="true">Select country</option>
    <% foreach(var country in Model.Countries) { %>
        <option value="<%= country.Id %>"><%= country.Name %></option>
    <% } %>
</select><br/>
<select id="dropdown2"></select>

at the end of the page

<script>

 $(document).ready( function() {

    $("#dropdown1").bind("change", function() {
        // everytime the value of the dropdown 1 is changed, do this:

        var countryId = $("#dropdown1").val();

        $.get("/country/getDistricts", { 'country' : countryId }, function(data) { 
            $("#dropdown2").empty(); // clear old values if exist

            var options = "";

            for(i = 0; i < data.length; i++) { // build options
                options += ("<option value='" + data[i].districtId + "'>" + data[i].districtName + "</option>");
            }
            $("#dropdown2").append(options);
        });
    });
 });

</script>

in your Action at country Controller

public ActionResult getDistricts(string country)
{
    List<Districts> districts = dbRepository.GetDistrictsByCountryId(country);

    return Json(districts, JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

Comments

-2

There are two possible ways to achieve this.

Either put all combinations in html and use javascript to change the contents of the second combo upon selection in first combo.

Or setup AutoPostback on the first combo and fill the second one at server-side depending on the selected value of first combo.

2 Comments

There is no "AutoPostBack" in asp.net MVC
I didn't say there was. You just have to do it on your own with javascript, that's why I said "setup AutoPostback" instead of "set AutoPostBack property to true".

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.