Как я могу получить несколько значений? - PullRequest
0 голосов
/ 08 февраля 2020

Я учусь ASP. NET MVC, я пытаюсь получить несколько выбранных значений флажков. Но когда я выбираю более одного значения, я получаю только одно значение. Пожалуйста, помогите мне: как я могу получить все выбранные значения?

Это мой метод класса:

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

Это мой 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>

Пожалуйста, предложите какое-нибудь решение - как я могу получить все выбранные значения флажков?

1 Ответ

1 голос
/ 08 февраля 2020

Модель сотрудника

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