jeudi 20 février 2020

MVC- selecting checkbox list with values from database

I'm creating a web application manages tasks using ASP.NET MVC database first approach database model

create .cshtml :

 @foreach (var emp in ViewBag.emp)
            {

                <input id="empchk"
                       name="empchk"
                       type="checkbox"
                       value="@emp.Value"
                       @*checked="@item.IsChecked"*@ />
                @emp.Text <br />

            }

create action :

      // GET: tasks/Create
            public ActionResult Create()
            { 
                ViewBag.emp = new SelectList(db.employees, "id", "emp_name");

                return View();
            }

 [HttpPost]
    public  ActionResult  Create([Bind(Include = "task_id,task_name,task_desc,created_by,dep,date,mail,notes,user,emp_task,state")] task task, HttpPostedFileBase postedFile, List<string> empchk)
        {
 if (ModelState.IsValid)
            {
       db.tasks.Add(task);
                    db.SaveChanges();

                emp_task emtask = new emp_task();

                foreach (var item in empchk)
                {
                    emtask.emp_id = Convert.ToInt32(item);
                    emtask.task_id = task.task_id;

                    receiver = db.employees.Where(x => x.id == emtask.emp_id).Select(x => x.email).First()+ " , " + receiver  ;
                    db.emp_task.Add(emtask);
                    db.SaveChanges();
                }
}

I have a problem in selecting checkbox with values from database and post the new checked list ( edit mode)

I use the following code line to select values from database , but how to select checkbox list based on this list ?

 var x = (from employee in db.employees join emptask in db.emp_task on employee.id equals emptask.emp_id where emptask.task_id == id select new { employee.id, employee.emp_name }).ToList();

I appreciate any help , thank you




Aucun commentaire:

Enregistrer un commentaire