【问题标题】:Populate a drop down list based on another drop down list selected value in MVC 4根据 MVC 4 中的另一个下拉列表选定值填充下拉列表
【发布时间】:2015-07-08 06:14:45
【问题描述】:

我已经提到 This ans 的 stackoverflow 它工作正常,但由于我在表单中采用了下拉列表,所以当第二个下拉列表填充第一个下拉列表中的选定值时,它会生效。如何保持该值??

这是我的代码。

查看

@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("country", ViewData["Id"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }


@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("state", ViewData["Id1"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }


@{ Html.BeginForm("Create", "User", FormMethod.Post, new { enctype = "multipart/form-data" }); }
@Html.DropDownList("city", ViewData["Id2"] as List<SelectListItem>, new { onchange = "this.form.submit();" })
@{ Html.EndForm(); }

控制器

 public ActionResult Create()
    {
        FillCountry();
        FillState();
        FillCity();
        return View();
    }
    [HttpPost]
    public ActionResult Create(User ur)
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "Insert into tblTest (Name,Email,MobileNo) values('" + ur.Name + "','" + ur.Email + "','" + ur.MobileNo + "')";
        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();
        con.Close();
        TempData["msg"] = "<script>alert('Inserted Successfully');</script>";
        ModelState.Clear();
        FillCountry();
        FillState();
        FillCity();
        return View();


    }
    public void FillCountry()
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tblCountry ";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
       
        ViewData["Id"] = li;
        
    }
    public void FillState()
    {
        int id = Convert.ToInt16(Request["country"]);
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tblState where cid='" + id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        ViewData["Id1"] = li;
    }
    public void FillCity()
    {
        int id = Convert.ToInt16(Request["state"]);
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tbl_cities where StateId='" + id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        li.Add(new SelectListItem { Text = "Select", Value = "0" });
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        ViewData["Id2"] = li;
    }

当我只使用两个下拉列表,即ddlCountryddlState 并从ddlCountry 中选择国家/地区时,我的ddlSates 正在正确填充,但从ddlCountry 中选择的国家/地区正在发生变化。

【问题讨论】:

  • 与问题无关,但尽量避免使用字符串连接的查询构造,而是使用参数化查询来避免 SQL 注入的危险。
  • @downvoter 有什么理由拒绝投票吗??
  • int id = Convert.ToInt16(Request["Id1"]); 将失败,因为您没有名称属性为name="Id1" 的控件,因此Request["Id1"] 将始终为空。我猜你的模型没有名为Id 的属性,所以你没有绑定到任何东西,在这种情况下你需要设置SelectListItemSelected 属性。我强烈建议您访问 MVC 站点并学习一些基本教程。
  • @Navy,那么您的问题中有错字 - 第二个下拉菜单必须是 @Html.DropDownList("Id1", ...) - 而不是 "Id"
  • 我在第一条评论中指出了如何做到这一点。但是您的代码包含了我能想到的 MVC 中所有最糟糕的做法。在继续之前,您需要学习一些基础知识。

标签: c# asp.net-mvc-4


【解决方案1】:

做到了,效果很好

控制器

public ActionResult Index()
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tbl_country ";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        ViewData["country"] = li;
        return View();
    }
    public JsonResult StateList(int Id)
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tbl_states where cid='" + Id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        return Json(li, JsonRequestBehavior.AllowGet);
    }
    public JsonResult Citylist(int id)
    {
        string str = @"Data Source=DEV_3\SQLEXPRESS;Initial Catalog=DB_Naved_Test;Integrated Security=True";
        SqlConnection con = new SqlConnection(str);
        string query = "select * from tbl_cities where stateid='" + id + "'";
        SqlCommand cmd = new SqlCommand(query, con);
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        List<SelectListItem> li = new List<SelectListItem>();
        while (rdr.Read())
        {
            li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
        }
        return Json(li, JsonRequestBehavior.AllowGet);
    }

查看

@using (Html.BeginForm())
{ @Html.DropDownList("Country", ViewData["country"] as SelectList, "Select Country", new { id = "Country", style = "width: 150px;" })<br />
<select id="State" name="state" , style="width: 150px;"></select><br />
<select id="city" name="City" , style="width: 150px;"></select><br />
}
@Scripts.Render("~/bundles/jquery")
<script type="text/jscript">
$(function ()
{
    $('#Country').change(function ()
    {        
        $.getJSON('/Cascading/StateList/' + $('#Country').val(), function (data)
        {
            var items = '<option>Select 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 City</option>';
            $.each(data, function (i, city)
            {
                items += "<option value='" + city.Value + "'>" + city.Text + "</option>";
            });
            $('#city').html(items);
        });
    });
});

【讨论】:

  • 如何在不使用json的情况下获得城市和州的价值
【解决方案2】:

你可以像下面这样使用jquery

$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>


<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>

【讨论】:

    【解决方案3】:
                      <div class="col-md-4">
                        <div class="form-group">
                            <label for="validationCustom04">
                      @Html.LabelFor(model => model.LGAID)</label>
                           <select id="LocalID" name="LocalID" 
                         class="form-control" 
                      data-val="true" 
                   data-val-number="Select Local Government">
                               <option value="0">---Select--</option>
                           </select>
                            <div class="invalid-feedback">
                                @Html.ValidationMessageFor(model => model.LGAID, "", new { @class = "text text-danger" })
                            </div>
                        </div>
                    </div>
    

    【讨论】:

    • 为纯代码答案提供解释通常会使它们更有用。首先说明您的答案如何补充/增强以前的答案,或者它是否可以用作回答问题的新方法。
    【解决方案4】:
                      $("#State").change(function() {
                   var Id = $("#localID option:Selected").val();
                 $.getJSON('/ControllerName/ActionName/' + Id, 
               function (data) {
               var AddItem = '<option value="">---select from list--</option>';
            $.each(data, function (i, local) {
                AddItem += "<option value='" + local.LGAID + "'>" + local.LGAName + " 
                </option>"
            });
    
            $('#LocalID').html(AddItem);
               });
            });
    

    【讨论】:

    • 你能解释一下你的代码是如何回答这个问题的吗?
    【解决方案5】:
    [Route("PersonalData/localGoverntment")]
    public ActionResult ActionName(int Id)
    {
        DBEntities db = new DBEntities();
    
        List<LGA> LocalList = db.LGAs.ToList();
        List<LocalGModel> localModel = LocalList.Where(x => x.StateID == Id).Select(x => new LocalGModel { LGAID = x.LGAID, LGAName = x.LGAName }).ToList();
    
        return Json(localModel, JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      相关资源
      最近更新 更多