如何将下拉菜单转换为视图页面中的复选框

问题描述 投票:0回答:1

我正在使用动态复选框,我试图从另一个已经创建的表中获取CheckBox值。但是,当我为DropDownList编写代码时,它可以正常工作,但与CheckBox相同,则无法工作

  1. 以下是我的方法

    public IEnumerable<clsHobbyList> GetHobby()
            {
                List<clsHobbyList> lstHobby = new List <clsHobbyList>();
    
                using (SqlConnection con = new SqlConnection(ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("spAddHoby", con);
                    cmd.CommandType = CommandType.StoredProcedure;
    
                    con.Open();
                    SqlDataReader rdr = cmd.ExecuteReader();
    
                    while (rdr.Read())
                    {
                        clsHobbyList hby = new clsHobbyList();
                        hby.Id = Convert.ToInt32(rdr["Id"]);
                        hby.HobbyName = rdr["HobbyName"].ToString();
    
    
                        lstHobby.Add(hby);
                    }
                    con.Close();
                }
                return lstHobby;
            }
    
  2. 以下是我的控制器

     public ActionResult Create()
            {
                EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();
                clsHobbyList hby = new clsHobbyList();
                ViewBag.Hobby = new SelectList(objemployee.GetHobby(), "Id", "HobbyName");
    
                return View();
            }
    
  3. 这是我的查看页面,听到如何获取复选框?请给我建议一些解决方案

    <div class="form-group">
                @Html.LabelFor(model => model.Hobby, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
    
                    @Html.DropDownList("Hobby", null, htmlAttributes: new { @class = "form-control" })
    
                </div>
                @Html.ValidationMessageFor(model => model.Hobby, "", new { @class = "text-danger" })
            </div>
    

    -----------听到如何获得复选框------------------------------- -------------

c# asp.net-mvc checkboxlist
1个回答
0
投票

使用Foreach循环

@foreach (var item in Model.clsHobbyList)
            {
                <input type="checkbox" id="@item.Id" value="@item.HobbyName" text="@item.HobbyName" name="@item.HobbyName" />
                @item.HobbyName
            }
© www.soinside.com 2019 - 2024. All rights reserved.