jeudi 28 mars 2019

how to get selected checkboxes

I am using Checkbox in MVC my CShtml is like this :

List mylist1 = ViewBag.hobbies;

foreach (var h in mylist1)
{
                <tr>
                    <input type="checkbox" name="hobbies" value="@h.Hobbie" class="checkboxTwo" style="background-color:aliceblue" />@h.Hobbie

                </tr>
}

Now i want check box list checked in Edit mode .

In Edit Mode of Controller i written this code:

public ActionResult Edit(int? id)

    {
        TestEntities db = new TestEntities();
        ViewBag.hobbies = db.hobbies.ToList();

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        string[] times = (employee.hobbies).Split(',');
      //  string hobbies = collection["hobbies"];
       // collection["hobbies"] = string hobbies;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (var item in employee.hobbies)
        {

            if (item)
            {
                //append each checked records into StringBuilder
                sb.Append(item + ",");

            }


        }

public ActionResult Edit(int? id)

    {
        TestEntities db = new TestEntities();
        ViewBag.hobbies = db.hobbies.ToList();

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Employee employee = db.Employees.Find(id);
        string[] times = (employee.hobbies).Split(',');
      //  string hobbies = collection["hobbies"];
       // collection["hobbies"] = string hobbies;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        foreach (var item in employee.hobbies)
        {

            if (item)
            {
                //append each checked records into StringBuilder
                sb.Append(item + ",");

            }


        }

M expecting checkbox list get checked in Edit Modeenter image description here




Aucun commentaire:

Enregistrer un commentaire