ASP.NET MVC - 局部视图中的Post动作返回null ViewModel

时间:2014-06-26 09:17:45

标签: c# asp.net-mvc-4 viewmodel partial-views

我正在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)。这是我的视图和我的POST方法:

@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 mehtod:

    [HttpPost]
    public ActionResult DaysOff(**DaysOffViewModel dovm**=> the List "DaysOff" has no item at all)
    {
        //some code
    }

正如我所说,在我的POST中,mehtod获得了一个具有空列表的DaysOffViewModel。它可能是什么?

1 个答案:

答案 0 :(得分:4)

相反,每个循环用于循环,如下所示:

@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>
 }