问题级联下拉列表,生成的下拉列表未将选定值发布到服务器

Maz*_*mal 6 c# asp.net ajax asp.net-mvc

这是我在图像中的观点 在此输入图像描述

代码工作正常,但......

当我提交表单时,它只发送第一个下拉列表的值(我在浏览器网络上检查了收到的参数),当我查看页面源时它也没有显示我使用ajax函数生成的生成选项.

这是我的代码

生成我的第一个dropdownList的操作

public ActionResult TwoDropDownList()
{
    HotelContext H = new HotelContext();
    ViewBag.DropDownListOne = new SelectList(H.Continent.ToList(), "Id", "Name");
    return View();
}
Run Code Online (Sandbox Code Playgroud)

返回第二个下拉列表数据的json的操作

[HttpPost]
public JsonResult UpdateCountryDropDownList(int ContinentId)
{
    HotelContext H = new HotelContext();
    List<SelectListItem> CountryNames = new List<SelectListItem>(); 
    List<Country> Co = H.Country.Where(x => x.ContinentId == ContinentId).ToList();
    Co.ForEach(x =>
    {
        CountryNames.Add(new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
    });   
    return Json(CountryNames , JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

我的Ajax电话

@model Hotel.Models.Continent
 <script>
      $(document).ready(function () {
          $("#Name").change(function () {
              var ContinentoId = $(this).val();
              $.ajax({
                  type: "POST",
                  dataType: "json",
                  data: { ContinentId: ContinentoId },
                  url: '@Url.Action("UpdateCountryDropDownList","Home")',
                  success: function (result) {
                      var Country = "<select id='ddlCountry'>";
                      Country = Country + '<option value="">--Select--</option>';
                      for (var i = 0; i < result.length; i++) {
                          Country = Country + '<option value=' + result[i].Value + '>' + result[i].Text + '</option>';
                      }
                      Country = Country + '</select>';
                      $('#Countries').html(Country);
                  },
                  error: function (xhr, ajaxOptions, thrownError) {
                      console.log(arguments)
                  }
              });
          });
      })
</script>
Run Code Online (Sandbox Code Playgroud)

我的看法

@using(Html.BeginForm()){
    SelectList se = ViewBag.DropDownListOne;
    @Html.DropDownListFor(x=>x.Name,se,"--Select--")
    <div id ="Countries">
       @Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
    </div>
    <input type="submit" value="submit" style="margin-top:100px;" />
}
Run Code Online (Sandbox Code Playgroud)

HTTPPost动作

[HttpPost]
public string TwoDropDownList(string Name, string ddlCountry)
{
    if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(ddlCountry))
    {
        return ("you must select Both");
    }
    else
        return ("everything is working fine");
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你已经有一个<select>元素name="ddlCountry"(由@Html.DropDownList("ddlCountry", new List<SelectListItem>(), "--Select--")ajax调用生成,你覆盖它并创建一个<select>没有name属性的新元素(因此它的值不会被回发.

在成功回调中,您应该创建<option>元素并将它们附加到现有元素<select>

success: function (result) {
    var country = $('#ddlCountry); // get the existing element
    country.empty().append($('<option></option>').val('').text('--Select--'));
    $.each(result, function(index, item) {
        country.append($('<option></option>').val(item.Value).text(item.Text));
    });
}
Run Code Online (Sandbox Code Playgroud)

旁注:您的方法应该返回一组匿名对象,而不是在您不使用它们时,无需通过线路SelectListItem发送额外数据(其他属性SelectListItem).