繁体   English   中英

根据先前选择的项目asp.net mvc填充下拉列表

[英]Populating dropdownlist based on previous selected item asp.net mvc

我试图根据先前选择的项目填充DropDownList 为此,我创建了三个模型

国家模型:

[Key]
public int CountryId { get; set; }
public string CountryName { get; set; }

public virtual ICollection<State> States { get; set; }

状态模型:

[Key]
public int StateId { get; set; }
public string StateName { get; set; }
[ForeignKey("Country")]
public int CountryId { get; set; }

public virtual Country Country { get; set; }
public virtual ICollection<City> Citys { get; set; }

城市模型:

[Key]
public int CityId { get; set; }
public string CityName { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }

public virtual State State { get; set; }

这是我的控制器:

private ProjectContext db = new ProjectContext();
//
// GET: /CascadingDropdown/

public ActionResult Index()
{
    ViewBag.CountryId = new SelectList(db.Countrys, "CountryId", "CountryName");
    return View();
}

public JsonResult StateList(int Id)
{
    var state = from s in db.States
                where s.CountryId == Id
                select s;
    return Json(new SelectList(state.ToArray(), "StateId", "StateName"), JsonRequestBehavior.AllowGet);
}

public JsonResult Citylist(int id)
{
    var city = from c in db.Citys
               where c.StateId == id
               select c;
    return Json(new SelectList(city.ToArray(), "CityId", "CityName"),   JsonRequestBehavior.AllowGet);
}
public IList<State> Getstate(int CountryId)
{
    return db.States.Where(m => m.CountryId == CountryId).ToList();
}

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadClassesByCountryId(string CountryName)
{
    var stateList = this.Getstate(Convert.ToInt32(CountryName));
    var stateData = stateList.Select(m => new SelectListItem()
    {
        Text = m.StateName,
        Value = m.CountryId.ToString(),
    });
    return Json(stateData, JsonRequestBehavior.AllowGet);
}

然后是我的脚本:

$(function () {
  $('#Country').change(function () {
    $.getJSON('/Cascading/StateList/' + $('#Country').val(), function (data) {
      var items = '<option>Select a State</option>';
      $.each(data, function (i, state) {
          items += "<option value='" + state.Value + "'>" + state.Text + "</option>";
      });
      $('#State').html(items);
    });
  });

  $('#State').change(function () {
    $.getJSON('/Cascading/Citylist/' + $('#State').val(), function (data) {
      var items = '<option>Select a City</option>';
      $.each(data, function (i, city) {
        items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
      });
      $('#city').html(items);
    });
  });
});

最后,我用以下视图显示它:

@model Test_restriction.DAL.ProjectContext
@using (Html.BeginForm())
{
  @Html.DropDownList("Country", ViewBag.CountryId as SelectList, "Select a       Country",      new { id="Country" })<br />
  <select id="State" name="state"></select><br />
  <select id="city" name="City"></select><br />
}

@section js
{
  <script src="~/Scripts/Testing.js" type="text/javascript"></script>
}

因此,我希望将所有代码都清楚地发布,现在的问题是,只有第一个包含国家/地区的DropDownList被填充,而其他两个DropDownList仍然为空。 有人可以帮忙找出问题所在吗?

谢谢!

尝试这个

视图

@model Test_restriction.DAL.CountryModel

 <script type="text/javscript">
  $(function(){
    $('#ddlcountry').change(function () {
        var sub = $('#ddlstate').val();
        if (sub != null && sub != "") {
            $('#ddlstate').html(' <option value="">--Select Topic--</option>');
            $.ajax({
                url: '/Cascading/StateList',
                data: { id: sub },
                type: 'post',
                success: function (data) {
                    if (data != null && data != "") {
                        $.each(data, function (i, item) {
                            $("#ddlstate").append($("<option></option>").val(item.value).html(item.text));
                        });
                    }
                    else {
                        $('#ddlstate').html(' <option value="">--Select State--</option>');
                    }
                }
            });
        }
        else {
            $('#ddlstate').html(' <option value="">--Select State--</option>');
        }
    });
  });
 </script>      

@Html.DropDownListFor(m => m.subject_id, (SelectList)ViewBag.Countries, "--Select Country--", new { @Class = "form-control", id = "ddlcountry" })
<select id="ddlstate" name="state_id" class="form-control">
    <option value="">--Select State--</option>
</select>

控制者

public ActionResult Index()
{
    ViewBag.countries = new SelectList(db.Countrys, "CountryId", "CountryName");
    return View();
}


 public JsonResult StateList(int Id)
{
    var state = (from s in db.States
                where s.CountryId == Id
                select s).ToList();
     var list = state.Select(m => new { value = m..StateId, text = m.stateName });
    return Json(list, JsonRequestBehavior.AllowGet);
}

对城市下拉菜单使用相同的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM