c# - framework - full calendar asp net mvc
¿Cómo agregar casillas de verificación a cada día en esta vista de calendario? (1)
Tener esto dentro del ciclo foreach:
@Html.CheckBoxFor(m => m.CompletionRequested , new { @checked = evt.CompletionRequested });
ACTUALIZACIÓN: responde a tu pregunta en comentarios. Haga HttpPost al controlador y pase los datos del modelo.
[HttpPost]
public ActionResult CalendarIndex(CalendarArg model)
{
// Check that model is valid
if(ModelState.IsValid)
{
// CODE here to update Database
return RedirectToAction("Index"); // or where ever you want to go
}
else
{
return View(model); // Return back to View, model is not valid
}
}
ACTUALIZACIÓN 2:
Si desea agregar un nombre de clase, puede hacerlo así:
@Html.CheckBoxFor(m => m.CompletionRequested , new { @checked = evt.CompletionRequested, @class = "checkbox" });
O puede agregar css así:
input[type="radio"]:checked
{
// css when radio button is selected
}
input[type="radio"]
{
// css when radio button is not selected
}
Estos estilos CSS son globales, por lo que cada elemento de entrada con tipo de radio obtendrá estilos.
Y cuando quiera cambiar los cambios en el contexto db, primero debe encontrar el actual del contexto. A continuación, agregue el valor verdadero a la propiedad CompletionRequested y luego llame al método SaveChanged de su contexto. Tu primera pregunta fue obtener casillas de verificación en tu vista de calendario, no cómo guardar cambios en db. Esa es otra pregunta.
Estoy intentando agregar una función de casilla de verificación simple a cada día en mi vista de calendario. Debe estar en línea con el estilo del calendario actual y cuando se selecciona un bool, debe poder guardar los cambios en la base de datos. Cualquier sugerencia sera apreciada.
Mi principal problema en este momento es que las casillas de verificación que están siendo seleccionadas no se guardan en el db.
Controller.cs
private F2FW _db = new F2FW();
[HttpGet]
public ActionResult CalendarIndex()
{
List<Event> events = new List<Event>();
Project.Models.Calendar calendar = new Project.Models.Calendar();
calendar.SetDate(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
calendar.View(@"~/Views/Patient/Calendar.cshtml");
calendar.ViewData.Add("events", events);
ViewBag.calendar = calendar.Render();
return View(calendar);
}
[HttpPost]
public ActionResult CalendarIndex(User user, CalendarArg calArg, int dayCounter, string[] cbx_day, Patient patient, SessionExercise sessionExercise)
{
SessionInformation sessiondata = new SessionInformation();
Session lastsession = db.Sessions.Where(s => s.ActiveUserID == user.UserID).OrderByDescending(e => e.StartedAt).FirstOrDefault();
calArg.CompletedToday = DateTime.Today;
if (ModelState.IsValid)
{
if (calArg.CompletionRequested == false)
{
//do nothing!
}
else if (calArg.CompletionRequested == true)
{
if (sessiondata.Completed == true)
{
if (sessionExercise.FinishedAt == calArg.Past)
{
List<Event> events = new List<Event>();
events.Add(new Event() { Title = "Exercises Completed", EventDate = DateTime.Now.AddDays(0), Type = Event.EventType.Vacation }); //green
}
}
if (sessiondata.Completed == false)
{
if (sessionExercise.FinishedAt == calArg.Past)
{
List<Event> events = new List<Event>();
events.Add(new Event() { Title = "Exercises Uncompleted", EventDate = DateTime.Now.AddDays(0), Type = Event.EventType.Critical }); //red
}
}
}
_db.SaveChanges();
return RedirectToAction("CalendarIndex"); // or where ever you want to go
}
else
{
return View(calArg);
}
}
public class Event
{
public string Title
{
get;
set;
}
public DateTime EventDate
{
get;
set;
}
public EventType Type
{
get;
set;
}
public enum EventType
{
Appointment,
Meeting,
Vacation,
Birthday,
Personal,
Critical
}
}
Model.Calendar.cs
public class Calendar
{
int _year;
int _month;
DateTime _selectedDate;
string _viewFile = "";
ViewDataDictionary _viewData = new ViewDataDictionary();
Func<DateTime, bool, string> _onDayRenderFunc = null;
public Calendar()
{
SetDate(DateTime.Now.Year, DateTime.Now.Month);
}
public void SetDate(int year, int month)
{
_year = year;
_month = month;
_selectedDate = new DateTime(_year, _month, 1);
}
public void SetDate(int year, int month, int day)
{
_year = year;
_month = month;
_selectedDate = new DateTime(_year, _month, day);
}
public DateTime Date
{
get
{
return _selectedDate;
}
}
public void OnDayRender(Func<DateTime, bool, string> func)
{
_onDayRenderFunc = func;
}
public void View(string viewFile)
{
_viewFile = viewFile;
}
public ViewDataDictionary ViewData
{
get
{
return _viewData;
}
}
public string Render()
{
string[] dayNames = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int daysInMonth = DateTime.DaysInMonth(_year, _month);
int pYear = _year;
int pMonth = _month;
if ((_month - 1) < 1)
{
--pYear;
pMonth = 12;
}
else
{
--pMonth;
}
int daysInPrevMonth = DateTime.DaysInMonth(pYear, pMonth);
DateTime d1 = new DateTime(_year, _month, 1);
int dayPos = (int)d1.DayOfWeek;
daysInPrevMonth -= dayPos - 1;
StringBuilder control = new StringBuilder();
control.Append("<table cellpadding=/"0/" cellspacing=/"0/">/n<thead>/n<tr>/n");
for (int i = 0; i < dayNames.Length; i++)
{
control.Append(string.Format("<th>{0}</th>/n", dayNames[i]));
}
control.Append("</thead>/n<tbody>/n");
int totalDaysInMonth = daysInMonth + dayPos;
int col = 0;
int day = 0;
string cellValue = "";
for (int idx = 0; idx < totalDaysInMonth; idx++)
{
if (col == 0)
{
control.Append("<tr>/n");
}
if (idx >= dayPos)
{
++day;
if (_viewFile == "")
{
cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(_year, _month, day), true) : day.ToString();
}
else
{
ViewData.Model = new CalendarArg() { Date = new DateTime(_year, _month, day), SelectedDate = _selectedDate, CurrentMonth = true };
cellValue = this.Parse(_viewFile);
}
control.Append(string.Format("<td data-day=/"{0}/" data-month=/"{1}/" data-year=/"{2}/">{3}</td>/n", day, _month, _year, cellValue));
}
else
{
if (_viewFile == "")
{
cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(pYear, pMonth, daysInPrevMonth), false) : daysInPrevMonth.ToString();
}
else
{
ViewData.Model = new CalendarArg() { Date = new DateTime(pYear, pMonth, daysInPrevMonth), SelectedDate = _selectedDate, CurrentMonth = false };
cellValue = this.Parse(_viewFile);
}
control.Append(string.Format("<td>{0}</td>/n", cellValue));
++daysInPrevMonth;
}
if (col == 6)
{
control.Append("</tr>/n");
col = 0;
continue;
}
++col;
}
if (col < 7)
{
int nextMonthDay = 1;
for (int c = col; c < 7; c++)
{
if ((_month + 1) > 12)
{
++_year;
_month = 1;
}
else
{
++_month;
}
if (_viewFile == "")
{
cellValue = _onDayRenderFunc != null ? _onDayRenderFunc(new DateTime(_year, _month, nextMonthDay), false) : nextMonthDay.ToString();
}
else
{
ViewData.Model = new CalendarArg() { Date = new DateTime(_year, _month, nextMonthDay), SelectedDate = _selectedDate, CurrentMonth = false };
cellValue = this.Parse(_viewFile);
}
control.Append(string.Format("<td>{0}</td>/n", cellValue));
++nextMonthDay;
}
control.Append("</tr>/n");
}
control.Append("</tbody>/n</table>/n");
return control.ToString();
}
private string Parse(string viewFile)
{
using (var sw = new StringWriter())
{
ControllerContext ctx = new System.Web.Mvc.ControllerContext();
ctx.HttpContext = new HttpContextWrapper(HttpContext.Current);
RazorView view = new RazorView(ctx, viewFile, "", false, null);
TempDataDictionary tdd = new TempDataDictionary();
var viewContext = new ViewContext(ctx, view, ViewData, tdd, sw);
view.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
Model.CalendarArg.cs
public class CalendarArg
{
public DateTime SelectedDate { get; set; }
public DateTime Date { get; set; }
public bool CurrentMonth { get; set; }
public bool CompletionRequested { get; set; }
public DateTime CompletedToday { get; set; }
}
View.CalendarIndex.cshtml
<style>
table {
width: 100%;
border: 0px;
border-collapse: collapse;
border: 1px solid #EEE;
}
table thead tr th {
font-family: Tahoma;
font-weight: normal;
color: #666;
}
table tbody tr td {
border: 1px solid #EEE;
width: 14%;
}
table tbody tr td .cell1, .cell2 {
min-height: 150px;
height: 100%;
}
table tbody tr td .selected_day h2 {
Color: #FFF;
background-color: #3498DB;
text-shadow: none;
}
table tbody tr td .cell1 {
background-color: #FFF;
}
table tbody tr td .cell1:hover h2 {
box-shadow: 1px 2px 3px #999;
}
table tbody tr td .cell2 {
background-color: #FCFCFC;
}
table tbody tr td .cell2 h2 {
color: #CCC;
}
table tbody tr td h2 {
font-family: Tahoma;
font-size: 20px;
font-weight: normal;
float: right;
margin: 0px;
padding: 6px;
color: #154B67;
background-color: #EEE;
display: block;
width: 25px;
height: 25px;
text-align: center;
text-shadow: 2px 1px #FFF;
}
table tbody tr td .evt {
font-family: Tahoma;
font-size: 12px;
margin: 5px;
padding: 10px;
color: #FFF;
border-radius: 2px;
}
table tbody tr td .clear {
clear: both;
}
.Meeting {
background-color: #DDD;
color: #222 !important;
}
.Personal {
background-color: #3498DB;
}
.Vacation {
background-color: #2ECC71;
}
.Appointment {
background-color: #F5AB35;
}
.Critical {
background-color: #F22613;
}
</style>@Html.Raw(ViewBag.calendar)
View.Calendar.cshtml
@model Project.Models.CalendarArg
@{
CalendarArg calArg = this.Model;
List<Project.Controllers.Event> events = (List<Project.Controllers.Event>)ViewData["events"];
string cssClass = calArg.CurrentMonth == true ? "cell1" : "cell2";
}
@if (calArg.Date.Day == calArg.SelectedDate.Day)
{
cssClass += " selected_day";
}
@if (calArg.Date.Day == calArg.Date.Day)
{
if (DateTime.Now <= calArg.Date)
{
@Html.CheckBoxFor(m => m.CompletionRequested, new { @checked = calArg.CompletionRequested });
}
}
<div class="@cssClass">
<h2>@calArg.Date.Day.ToString()</h2>
<div class="clear"></div>
@foreach (var evt in events)
{
if (evt.EventDate.Date.ToString("yyyyMMdd") == calArg.Date.ToString("yyyyMMdd"))
{
<div class="evt @evt.Type.ToString()">@evt.Title</div>
}
}
</div>
ACTUALIZAR
Al agregar esta línea de código a Calendar.cshtl
:
@if (calArg.Date.Day == calArg.Date.Day)
{
@Html.CheckBoxFor(m => m.CompletionRequested, new { @checked = calArg.CompletionRequested });
}
Sorprendentemente funciona, así que supongo que me gustaría saber cómo modificar la hoja de estilo css en el calendar index
para alinear las casillas con el diseño del calendario (es decir, en línea con el calendario y no solo encima) y cómo guardar los cambios en el bool a la db.