我正在开发一个网站在ASP。. NET MVC 4,在我的一个视图中,我有两个部分视图:
<div id="timeDaysAndBeds">
<div id="timeAndBeds">
@Html.Action("TimeAndBedParameters")
</div>
<div id="daysOff">
@Html.Action("DaysOff")
</div>
</div>
我的问题出现在第二个部分视图中。首先,这是我的GET方法:
[HttpGet]
public ActionResult DaysOff()
{
context = new SchedulingDataClassesDataContext();
List<DBDayOfWeekOff> listDaysOff = (from doff in context.DBDayOfWeekOff select doff).ToList();
DaysOffViewModel dovm = new DaysOffViewModel();
string[] tableDays = new string[]
{
"Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi","Dimanche"
};
List<DaysViewModel> listDays = new List<DaysViewModel>();
for (int i = 1; i <= tableDays.Length; i++)
{
DaysViewModel dvm = new DaysViewModel()
{
DayId = i,
DayName = tableDays[i - 1],
IsOff = false
};
dovm.DaysOff.Add(dvm);
}
foreach (DBDayOfWeekOff dayOff in listDaysOff)
{
dovm.DaysOff.ElementAt(dayOff.DayOfWeekNumber - 1).IsOff = dayOff.IsOff;
}
return PartialView(dovm);
}
这是我正在使用的视图模型:
public class DaysViewModel
{
public int DayId { get; set; }
public string DayName { get; set; }
public bool IsOff { get; set; }
}
public class DaysOffViewModel
{
public List<DaysViewModel> DaysOff { get; set; }
public DaysOffViewModel()
{
DaysOff = new List<DaysViewModel>();
}
}
当我调用我的GET方法时,我得到了我的局部视图一切看起来都很好。然而,当我试图调用我的POST方法时,我得到了一个空的DaysOff列表(count = 0)。
@model AstellasSchedulerV2.Models.DaysOffViewModel
@using (Html.BeginForm("DaysOff", "Home", FormMethod.Post, new { dovm = Model }))
{
<fieldset id="fsDaysOff">
<legend>Jours de fermeture</legend>
@foreach (AstellasSchedulerV2.Models.DaysViewModel dvm in Model.DaysOff)
{
<div class="editor-label">
@dvm.DayName
</div>
<div class="editor-field">
@Html.CheckBoxFor(d => dvm.IsOff)
</div>
}
<input id="registerDayOffBtn" type="submit" name="Enregistrer" value="Enregistrer" />
</fieldset>
}
我的POST方法:
[HttpPost]
public ActionResult DaysOff(**DaysOffViewModel dovm**=> the List "DaysOff" has no item at all)
{
//some code
}
正如我所说的,在我的POST方法中得到一个DaysOffViewModel,它有一个空列表。会是什么呢?
对于每个循环使用如下的for循环:
@for (int i=0; i<Model.DaysOff.Count; i++)
{
<div class="editor-label">
@Model.DaysOff[i].DayName
</div>
<div class="editor-field">
@Html.CheckBoxFor(d => Model.DaysOff[i].IsOff)
</div>
}