【问题标题】:Trigger Onchange event of a dropdownlistFor触发下拉列表的 Onchange 事件
【发布时间】:2017-03-23 05:01:00
【问题描述】:

我有 3 个下拉列表:国家、州和城市。在更改国家下拉菜单时,必须为所选国家/地区填充州下拉菜单,在更改状态下拉菜单时,必须为所选州填充城市下拉菜单。

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

这是我的代码:

.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);
}

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

更新 在@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 --");
                });

            }
        });
    }
}

【问题讨论】:

  • 您的具体问题是什么??
  • 建议您研究 this DotNetFiddle 中的代码 - 您将永远无法获得与当前实现正确的 2-way 模型绑定
  • @PRABA 我想用数据库中的选定值填充下拉列表
  • @Arti 您发布的代码不起作用吗?我认为您已经完成了使用数据库中的选定值填充下拉列表的代码。你在上面的代码中遇到了什么错误。
  • 我刚刚更新了小提琴 - 在 Index() 方法中,有 3 行注释掉的行来模拟从现有数据库值中设置的值。一次取消评论它们,然后查看结果。

标签: c# jquery asp.net-mvc


【解决方案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);

});

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

这会起作用。

【讨论】:

  • 感谢 Sagar 帮助。但是现在没有设置状态值。我已经用新问题更新了我的问题。
  • 对@sagar 的新问题有任何帮助吗?
  • @Arti 请稍候尝试了解您做错了什么
【解决方案2】:

我已经在@StephenMuecke cmets 的帮助下解决了这个问题。

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

代码:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多