0

I'm learning ASP.NET MVC, I'm trying to get multiple selected checkbox values. But when I select more than one value, I only get one value. Please help me: how can I get all selected values?

This is my class method:

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;
}

This is my controller:

[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);
}

This is my view:

     <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>

Please suggest some solution - how can I get all selected checkbox values?

5
  • 2
    Problem is all your checkboxes have same ID Commented Feb 8, 2020 at 6:48
  • what is emp.Hobby dataType ?! Commented Feb 8, 2020 at 6:58
  • I use Dynamic checkbox so ...@ Aleksa Ristic Commented Feb 8, 2020 at 7:05
  • because i Get Hobby value From Another table @ marc_s Commented Feb 8, 2020 at 7:29
  • 1
    SelectList only tracks a single selection. If you want multiple selections, you need to use MultiSelectList: learn.microsoft.com/en-us/dotnet/api/… Commented Feb 8, 2020 at 8:10

1 Answer 1

1

You need to use MultiSelectList, like this:

Employee Model

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; }
    ...
}

Controller

    [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");
    }

View

@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>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.