【问题标题】:How to show an empty dropdownlist when another one isn't selected未选择另一个下拉列表时如何显示一个空的下拉列表
【发布时间】:2016-06-08 13:36:10
【问题描述】:

我有两个都连接到数据库的下拉列表,一个称为 Distritos,另一个称为 Concelhos,当未选择 distritos 时,concelhos 应显示为空,当用户选择 distritos 的单词之一时,Concelhos 应该显示。我想让它像一个州与城市的关系。 这就是我的控制器中的内容:

public ActionResult getcidades(int? distrito = null)
{
    var concelho =
        Db.Concelhos.OrderBy(r => r.Nome) as IQueryable<Concelho>;

    if (distrito != null)
    {
        concelho = concelho.Where(t => t.Distritos.Id == distrito);                    
    }

    return Json(concelho.Select(r => new { Nome = r.Nome, r.Id }),  JsonRequestBehavior.AllowGet);
}

这是我的看法:

$("#Distrito").on("change", function() {
  var valor = $(this).val();

  $.ajax({
      type: "get",
      url: "@Url.Action("
      getcidades ","
      PiHelper ")",
      data: {
        distrito: valor
      }
    })
    .done(function(concelho) {
      var dropdown = $("#Concelho");

      dropdown.empty().focus();

      console.log(concelho, dropdown)
      for (var i = 0; i < concelho.length; i++) {
        $("<option>")
          .attr("value", concelho[i].Id)
          .text(concelho[i].Nome)
          .appendTo(dropdown);
      }
    })

})

【问题讨论】:

  • 有什么问题?
  • 当我不选择“Distrito”(表示状态)时,它应该显示一个空白(下拉列表中的空白区域)“Cidade”(Cidade 表示城市)。
  • 您需要编辑您的问题来解释问题。如果您在第一个下拉列表中选择null 选项,那么它会调用您的控制器方法,该方法返回所有Concelhos 您应该测试null,如果是这样,只需清空第二个下拉列表而不调用该方法。然后将控制器代码更改为public ActionResult getcidades(int distrito) { var concelho = Db.Concelhos.OrderBy(r =&gt; r.Nome)..Where(t =&gt; t.Distritos.Id == distrito); return Json(....); }

标签: c# jquery asp.net-mvc-4 drop-down-menu


【解决方案1】:

试试这个:

$('#distritos').each(function() {
    if ($(this).not(':selected')) 
    {
       $('#concelhos').val(0);
    }
});

if ($('#distritos :selected').length == 0)
{
    $('#concelhos options').remove();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多