如何获得多个值?

How can I get multiple values?

我正在学习 ASP.NET MVC,我正在尝试获取多个 selected 复选框值。但是当我 select 多个值时,我只得到一个值。请帮助我:如何获得所有 selected 值?

这是我的class方法:

public void AddEmployee(Employee emp)
{
    using (SqlConnection con = new SqlConnection(ConnectionString))
    {
        SqlCommand cmd = new SqlCommand("spaddEmployee", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@FirstName", emp.FirstName);
        cmd.Parameters.AddWithValue("@LastName", emp.LastName);
        cmd.Parameters.AddWithValue("@Gender", emp.Gender);
        cmd.Parameters.AddWithValue("@DOB", Convert.ToDateTime(emp.DOB));
        cmd.Parameters.AddWithValue("@Hobby",string.Join(",",emp.Hobby));
        cmd.Parameters.AddWithValue("@Photo", emp.Photo);
        cmd.Parameters.AddWithValue("@City", emp.City);

        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
}

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.Hobby = rdr["Hobby"].ToString();

            lstHobby.Add(hby);
        }

        con.Close();
    }

    return lstHobby;
}

这是我的控制器:

[HttpGet]
public ActionResult Create()
{
    EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();
    Employee emp = new Employee();

    ViewBag.Hobby = new SelectList(objemployee.GetHobby(), "Id", "Hobby");
    return View(emp);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind] Employee emp, HttpPostedFileBase file)
{
    EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();
    objemployee.GetHobby();

    if (file != null)
    {
        string pic = Path.GetFileName(file.FileName);
        string path = Path.Combine(Server.MapPath("~/Upload/"), pic);
        // file is uploaded
        file.SaveAs(path);
        emp.Photo = "/Upload/" + pic;
    }

    if (ModelState.IsValid)
    {
        ViewBag.Hobby = new SelectList(objemployee.GetHobby(), "Id", "Hobby");
        objemployee.AddEmployee(emp);
        return RedirectToAction("Index");
    }

    return View(emp);
}

这是我的观点:

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

                    @foreach (var item in ViewBag.Hobby)
                    {
                        <input type="checkbox" id="Hobby" name="Hobby" value="@item.Text" />
                        @item.Text

                    }
                </div>
                @Html.ValidationMessageFor(model => model.Hobby, "", new { @class = "text-danger" })
            </div>

请提出一些解决方案 - 如何获得所有 selected 复选框值?

你需要使用MultiSelectList,像这样:

员工模型

public class Employee
{
    public Employee()
    {
        SelectedHobbies = new List<int>();
        ...
    }
    [Display(Name = "Please Select Hobbies")]
    public List<int> SelectedHobbies { get; set; }
    public MultiSelectList AvailableHobbies { get; set; }
    ...
}

控制器

    [HttpGet]
    public ActionResult Create()
    {
        EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();
        Employee emp = new Employee()
        {
            AvailableHobbies = new MultiSelectList(objemployee.GetHobby(), "Id", "Hobby")
        };

        return View(emp);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Employee emp)
    {
        var selectedHobbies = emp.SelectedHobbies;
        ...
        return RedirectToAction("Index");
    }

查看

@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    ...
    <div class="form-group row">
        @Html.LabelFor(model => model.SelectedHobbies, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @foreach (var item in Model.AvailableHobbies)
            {
                <div class="checkbox">
                    <label>
                        <input type="checkbox"
                           name="SelectedHobbies"
                           value="@item.Value"
                           @if (Model.SelectedHobbies.Contains(Int32.Parse(item.Value))) { <text> checked </text> } /> @item.Text
                    </label>
                </div>
            }
        </div>
    </div>
    ...
    <div class="row">
        <input type="submit" value="Create" />
    </div>
}