dropdownlistFor的Trigger Onchange事件

时间:2017-03-23 05:01:01

标签: c# jquery asp.net-mvc

我有3个下拉列表:国家,州和城市。在国家下降的变化,国家下降必须填写选定的国家,在国家下降的变化,城市下降必须填充选定的州。

从UI更改下拉列值时,功能有效。现在我想用存储在数据库中的选定值填充下拉列表。即。如果我的数据库的值为countryId = 1,stateId = 5,cityId = 2,那么我的下拉列表应该相应地填充。当为其设置选定值时,下拉onchanhge必须直接调用。但是,第一次下拉菜单(国家/地区下拉菜单)的值已设置,但州和城市未设置值,因为未触发更改国家/地区。

这是我的代码:

.cshtml

<div class="row clearfix">
    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
        <label>Country</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick"} )
            </div><label id="CountryListLable" style="color:red;"></label>

        </div>
    </div>

    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>State</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                <select id="ddState" class="form-control show-tick">
                    <option>-- Please select --</option>
                </select>
            </div>
            <label id="StateListLable" style="color:red;"></label>
        </div>
    </div>
    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>City</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                <select id="ddCity" name="ddCity" class="form-control show-tick">
                    <option value="0">-- Please select --</option>
                </select>
            </div>
            <label id="CityListLable" style="color:red;"></label>
        </div>
    </div>
</div>

Jquery的:

 $('#CountryId').change(function () {
        //alert($(this));
        var cN;
        var UserType = $(this).data('type');

            $('#ddState').selectpicker();
            $('#ddState').empty();
            $('#ddState').selectpicker('refresh');
            $('#ddState').append("<option>-- Please select --</option>");
            cN = $('#CountryId').val();
        if (cN === '') {
            return false;
        } else {
            $.ajax({
                url: "/AdminUser/GetStatesForCountry?countryId=" + cN, success: function (result) {
                    console.log(result);
                    $.each(result, function (key, value) {

                            $('#ddState')
                               .append($("<option></option>")
                                          .attr("value", value.stateId)
                                          .text(value.stateName));
                            $('#ddState').selectpicker('refresh');
                            $('#ddState').selectpicker('val', "-- Please select --");
                    });

                }
            });
        }
    });

    $('#ddState').change(function () {
        var UserType = $(this).data('type');

            $('#ddCity').selectpicker();
            $('#ddCity').empty();
            $('#ddCity').selectpicker('refresh');
            $('#ddCity').append("<option>-- Please select --</option>");
            cN = $('#ddState').val();
        if (cN === '') {
            return false;
        } else {
            $.ajax({
                url: "/AdminUser/GetCitiesForState?StateId=" + cN, success: function (result) {
                    console.log(result);
                    $.each(result, function (key, value) {

                            $('#ddCity')
                             .append($("<option></option>")
                                        .attr("value", value.cityId)
                                        .text(value.cityName));
                            $('#ddCity').selectpicker('refresh');
                            $('#ddCity').selectpicker('val', "-- Please select --");
                    });

                }
            });
        }
    });

控制器代码

var countryData = new List<CountryData>();
IEnumerable<SelectListItem> countryList = new List<SelectListItem>();
countryData = (List<CountryData>)HttpContext.Cache.Get("countryResponse");
if (countryData == null)
{
    string response = Service.APIHelper_GET(StringConstants.GetCountryDetails);
    if (!response.Equals("Internal Server Error."))
    {
        countryData = new JavaScriptSerializer().Deserialize<List<CountryData>>(response);
        HttpContext.Cache.Insert("countryResponse", countryData);
    }
}
countryList = countryData.Select(m => new SelectListItem() { Text = m.countryName, Value = m.countryId.ToString() });

ViewBag.country = countryList;//new SelectList(countryList);


public JsonResult GetStatesForCountry(int countryId)//get states for countryid = id 
{
    Session["CountryId"] = countryId;
    return Json(getStateList(countryId), JsonRequestBehavior.AllowGet);
}

public List<State> getStateList(int countryId)
{
    var stateList = new List<State>();
    stateList = (List<State>)HttpContext.Cache.Get("StateResponseForCountry_" + countryId);
    if (stateList == null)
    {
        var response = (List<CountryData>)HttpContext.Cache.Get("countryResponse"); //this wont b null bcz on page load putting country list to chache
        foreach (var item in response)
        {
            if (item.countryId == countryId)
            {
                stateList = item.states;
            }
        }
        HttpContext.Cache.Insert("StateResponseForCountry_" + countryId, stateList);
    }
    return stateList;
}


public JsonResult GetCitiesForState(int StateId)
{
    var cityList = new List<City>();

    cityList = (List<City>)HttpContext.Cache.Get("CityResponseForState_" + StateId);
    if (cityList == null)
    {
        List<State> stateList = getStateList(Convert.ToInt32(Session["CountryId"]));

        foreach (var item in stateList)
        {
            if (item.stateId == StateId)
            {
                cityList = item.cities;
            }
        }
        HttpContext.Cache.Insert("CityResponseForState_" + StateId, cityList);
    }
    return Json(cityList, JsonRequestBehavior.AllowGet);
}

以下是更好地了解我的问题的方案: 我有一个创建用户页面,用户可以在其中选择级联下拉列表(国家,州,城市)并将选定值保存到数据库。问题出在编辑用户,我需要根据选定的值填充下拉列表。即。我需要使用数据库中的选定值填充状态下拉列表。

更新 在@Sagar的解决方案的帮助下,我设法为国家/地区下拉菜单设置了选定的值。但州和城市的下降仍未确定。这是更新的代码:

CSHTML

<div class="row clearfix">
    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
        <label>Country</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick" })
            </div><label id="CountryListLable" style="color:red;"></label>

        </div>
    </div>

    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>State</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.StateId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { @class = "form-control show-tick" })
            </div>
            <label id="StateListLable" style="color:red;"></label>
        </div>
    </div>
    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>City</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.fKCityId, Enumerable.Empty<SelectListItem>(), "-- Please select --", new { @class = "form-control show-tick" })
            </div>
            <label id="CityListLable" style="color:red;"></label>
        </div>
    </div>
</div>

Jquery的

$(document).ready(function () {
    var countryId = $('#CountryId').val();
    getStates(countryId);

    var StateId = $('#StateId').val();
    alert(StateId);/// here I am not getting correct value -- it passes stateId='-- Please select --'
    getCities(StateId);

    $('#CountryId').change(function () {
        var countryId = $(this).val();
        getStates(countryId);
    });

    $('#StateId').change(function () {
        var StateId = $(this).val();
        getCities(StateId);
    });

});

function getStates(countryId) {
    $('#StateId').selectpicker();
    $('#StateId').empty();
    $('#StateId').selectpicker('refresh');
    $('#StateId').append("<option>-- Please select --</option>");

    if (countryId === '') {
        return false;
    } else {
        $.ajax({
            url: "/AdminUser/GetStatesForCountry?countryId=" + countryId, success: function (result) {
                console.log(result);
                $.each(result, function (key, value) {

                    $('#StateId')
                       .append($("<option></option>")
                                  .attr("value", value.stateId)
                                  .text(value.stateName));
                    $('#StateId').selectpicker('refresh');
                    $('#StateId').selectpicker('val', "-- Please select --");
                });

            }
        });
    }
}

function getCities(stateId)
{
    $('#fKCityId').selectpicker();
    $('#fKCityId').empty();
    $('#fKCityId').selectpicker('refresh');
    $('#fKCityId').append("<option>-- Please select --</option>");
    if (stateId === '') {
        return false;
    } else {
        $.ajax({
            url: "/AdminUser/GetCitiesForState?StateId=" + stateId, success: function (result) {
                console.log(result);
                $.each(result, function (key, value) {

                    $('#fKCityId')
                     .append($("<option></option>")
                                .attr("value", value.cityId)
                                .text(value.cityName));
                    $('#fKCityId').selectpicker('refresh');
                    $('#fKCityId').selectpicker('val', "-- Please select --");
                });

            }
        });
    }
}

2 个答案:

答案 0 :(得分:1)

您必须在更改时调用ajax以及文档就绪,然后它将正常工作:

像:

创建一些常用函数,在就绪和更改状态下调用它:

function  getCountryStates(countryId){
//your ajax to get states by country 

}

$(document').ready(function () {

    var countryId = $('#CountryId').val();
    getCountryStates(countryId);

});

$('#CountryId').change(function () {

    var countryId = $(this).val();
    getCountryStates(countryId);

});

您必须按照上述相同流程来获取所选州的城市。

这样可行。

答案 1 :(得分:0)

我已经设法在@StephenMuecke评论的帮助下解决了这个问题。

我所要做的就是,在将模型传递给视图的同时填充下拉列表。

代码:

Model usersDetail = users.userDetail;
ViewBag.State = getStateList(usersDetail.CountryId).Select(m => new SelectListItem() { Text = m.StateName, Value = m.Id.ToString() });
ViewBag.City = getCityList(usersDetail.StateId).Select(m => new SelectListItem() { Text = m.CityName, Value = m.Id.ToString() });
return View(usersDetail);

并修改.cshtml以从viewbag填充州和城市:

<div class="row clearfix">
    <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label">
        <label>Country</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.CountryId, (IEnumerable<SelectListItem>)ViewBag.country, "-- Please select --", new { @class = "form-control show-tick" })
            </div><label id="CountryListLable" style="color:red;"></label>

        </div>
    </div>

    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>State</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.StateId, (IEnumerable<SelectListItem>)ViewBag.State, "-- Please select --", new { @class = "form-control show-tick" })
                @*<select id="State" class="form-control show-tick">
                    <option>-- Please select --</option>
                </select>*@
            </div>
            <label id="StateListLable" style="color:red;"></label>
        </div>
    </div>
    <div class="col-lg-1 col-md-1 col-sm-4 col-xs-5 form-control-label">
        <label>City</label>
    </div>
    <div class="col-lg-2 col-md-2 col-sm-8 col-xs-7">
        <div class="form-group">
            <div class="form-line">
                @Html.DropDownListFor(m => m.fKCityId, (IEnumerable<SelectListItem>)ViewBag.City, "-- Please select --", new { @class = "form-control show-tick" })
                @*<select id="ddCity" name="ddCity" class="form-control show-tick">
                    <option value="0">-- Please select --</option>
                </select>*@
            </div>
            <label id="CityListLable" style="color:red;"></label>
        </div>
    </div>
</div>