How to filter drop down list based on previous sel

2019-02-07 10:20发布

问题:

I am having two tables namely State and Country.These two are dropdowns in my view page. I am displaying dropdown values of each of them using an independent query. In table State i am having stateid and countryid. I need to filter state values based on country selection. And i even have a main table called Table which consists of ids of both state and country The following is the way i used to display,

enter code here

//To get state values

var query = (from i in dbContext.countries

                     join j in dbContext.States on i.Country_id equals j.Country_id

                     where j.State_id >= 0
                     select new
                     {
                         state = j.State_name}).ToArray//To get state values

enter code here

  var str = (from li in dbContext.countries

                           where li.Country_id >= 1
                           select new
                           {

                               country = li.Country_name}).ToArray();//To get country

values

And how can i query be for filtering the values usin main table "table".i am facing problem in writing query for filtering Is this possible using linq query ? Please suggest me how to do this Thanks

回答1:

This can be accomplished in different ways. One way is to get the server to return a filtered list of valid options via Ajax when the first dropdown is changed.

For example, assume this scenario: a View with two DropDownLists; one with countries and the other with states. The DropDownList with states is empty and disabled by default until a country is selected.

So you could have this Action in your controller:

public ActionResult Index()
{
    ViewBag.Country = new [] {
        new SelectListItem() { Text = "Venezuela", Value = "1" },
        new SelectListItem() { Text = "United States", Value = "2" }
    };
    return View();
}

And this View:

<div class="editor-field">
    @Html.DropDownList("Country")
    @Html.DropDownList("State", Enumerable.Empty<SelectListItem>(), "States", new { @disabled = "disabled" })
</div>

Now add a POST action in your controller. It receives the ID of the selected country and returns JSON containing a filtered list of states:

[HttpPost]
public ActionResult StatesByCountry(int countryId)
{
    // Filter the states by country. For example:
    var states = (from s in dbContext.States
                  where s.CountryId == countryId
                  select new
                  {
                      id = s.Id,
                      state = s.Name
                  }).ToArray();

    return Json(states);
}

The last thing is the client-side code. This example uses jQuery and sets up a change event listener on the country dropdown which calls the new controller action via Ajax. It then uses the returned values to update the 'State' DropDownList.

$(document).ready(function () {
    $('#Country').change(function () {
        $.ajax({
            url: '/Home/StatesByCountry',
            type: 'POST',
            data: { countryId: $(this).val() },
            datatype: 'json',
            success: function (data) {
                var options = '';
                $.each(data, function () {
                    options += '<option value="' + this.id + '">' + this.state + '</option>';
                });
                $('#State').prop('disabled', false).html(options);
            }
        });
    });
});