mercredi 14 mars 2018

Checkboxes for days of the week

I've been trying to make a check box for my form but I don't know how to do it. I hard-coded the checkbox and the values so they don't really go into the database.

[ ]Monday [ ]Tuesday etc...

Add view & Edit view:

 <div>
    <div>@Html.LabelFor(v => v.DaysAvailable):
        <div>
            @Html.CheckBox("Monday") Monday
            @Html.CheckBox("Tuesday") Tuesday
            @Html.CheckBox("Wednesday") Wednesday
            @Html.CheckBox("Thursday") Thursday
            @Html.CheckBox("Friday") Friday
            @Html.CheckBox("Saturday") Saturday
            @Html.CheckBox("Sunday") Sunday
        </div>
    </div>
</div>

Controller:

    [HttpGet]
    public ActionResult Add()
    {
        ViewBag.Departments = db.Departments.ToList();
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Add(Volunteer volunteer)
    {
        if (ModelState.IsValid)
            {
                db.Volunteers.Add(volunteer);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Departments = db.Departments.ToList();
            return View(volunteer);
    }

    [HttpGet]
    public ActionResult Edit(int? id)
    {
        if(id == 0)
            {
                return RedirectToAction("Index");
            }

            Volunteer volunteer = db.Volunteers.SingleOrDefault(v => v.VolunteerId == id);

            if(volunteer == null)
            {
                return RedirectToAction("Index");
            }

            ViewBag.Departments = db.Departments.ToList();
            return View(volunteer);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Volunteer volunteer)
    {
        if (ModelState.IsValid)
            {
                db.Entry(volunteer).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.Departments = db.Departments.ToList();
            return View(volunteer);
    }

Model:

[Display(Name = "Days Available")]
    public string DaysAvailable { get; set; }

I'm new at this framework so I'm really lost. :(




Aucun commentaire:

Enregistrer un commentaire