I'm new to .Net MVC and I just have a question regarding checkboxes. I want to make a checkbox list for the days of the week (Mon, Tue, etc) but I'm not really sure how to implement it.
Model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Features.Models
{
[Table("Volunteer")]
public class Volunteer
{
[Key]
public int VolunteerId { get; set; }
[Display(Name = "Days of Availability")]
public bool DaysAvailable { get; set; }
}
}
Controller:
[HttpGet]
public ActionResult Add()
{
try
{
ViewBag.Departments = db.Departments.ToList();
return View();
}
catch (Exception genericException)
{
ViewBag.ExceptionMessage = genericException.Message;
}
return View("~/Views/Errors/Details.cshtml");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Volunteer volunteer)
{
try
{
if (ModelState.IsValid)
{
db.Volunteers.Add(volunteer);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Departments = db.Departments.ToList();
return View(volunteer);
}
catch (DbUpdateException DbException)
{
ViewBag.DbExceptionMessage = DbException.Message;
}
catch (Exception genericException)
{
ViewBag.ExceptionMessage = genericException;
}
return View("~/Views/Errors/Details.cshtml");
}
View:
@model Assign1.Models.Volunteer
@{
ViewBag.Title = "Add";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Add a volunteer</h2>
@using (Html.BeginForm("Add", "Volunteer"))
{
@Html.AntiForgeryToken()
<div>
<div>@Html.LabelFor(v => v.DaysAvailable):
@Html.CheckBoxFor(v => v.DaysAvailable, new { name = "Monday"})
@Html.CheckBoxFor(v => v.DaysAvailable, new { name = "Tuesday" })
@Html.CheckBoxFor(v => v.DaysAvailable, new { name = "Wednesday" })
@Html.CheckBoxFor(v => v.DaysAvailable, new { name = "Thursday" })
@Html.CheckBoxFor(v => v.DaysAvailable, new { name = "Friday" })
@Html.CheckBoxFor(v => v.DaysAvailable, new { name = "Saturday" })
@Html.CheckBoxFor(v => v.DaysAvailable, new { name = "Sunday" })
</div>
</div>
For the views model, it doesn't show anything but the checkboxes (no words, just plain checkboxes).
Should I make a table from the database that holds the values for the days of the week? I'm not really sure what to do and I'm really lost.
Aucun commentaire:
Enregistrer un commentaire