未从Partial View MVC4发布的值

时间:2013-04-04 22:40:15

标签: asp.net-mvc razor asp.net-mvc-4 controller

由于某种原因,我的局部视图总是将空值返回给控制器。我尝试过几种不同的方式(包括编辑器模板)来实现它,但这是我的最新版本。

基本上我用jquery ui datepicker渲染视图。当用户选择日期时,我会渲染我的局部视图。部分视图正在正确呈现,但是当我提交局部视图时,它将一个空对象返回到控制器

查看型号:

public class Attendance
{
    public int RecordId { get; set; }
    public int GroupId { get; set; }
    public int MemberId { get; set; }
    public string MemberName { get; set; }
    public System.DateTime Date { get; set; }
    public bool Present { get; set; }

}

家长视图:

@{
    ViewBag.Title = "Take Attendance";
}

<h2>Take Attendance</h2>

@Html.Hidden("GroupId", (int)ViewBag.GroupId)

<div>
@Html.Label("Select A Date")
@Html.JQueryUI().Datepicker("attendanceDate",ViewBag.AttendanceDate)
                .OnSelect("attendanceDate.onSelect")
</div>

<div id="attendanceRecords">
</div>


@section scripts
{
    <script src="@Url.Content("../../Scripts/Views/TakeAttendance.js")" type="text/javascript"></script>
}

部分视图

@model IEnumerable<AT.Manager.Models.Attendance>

@using (Html.BeginForm("TakeAttendance", "Groups")) {
    @Html.ValidationSummary(true)

    <table>
        <tr>
            <th>Name</th>
            <th>Present?</th>
        </tr>
        @for (int i = 0; i < Model.Count(); i++ )
        {
            <tr>
                <td>@Html.DisplayFor(model => Model.ElementAt(i).MemberName)</td>
                <td>@Html.EditorFor(model => Model.ElementAt(i).Present)</td>
                <td>@Html.HiddenFor(model => Model.ElementAt(i).GroupId)</td>
                <td>@Html.HiddenFor(model => Model.ElementAt(i).MemberId)</td>
                <td>@Html.HiddenFor(model => Model.ElementAt(i).RecordId)</td>
            </tr>                      
        }
    </table>
    <p>
        <input type="submit" value="Create" />
    </p>
}

控制器操作:

public ActionResult TakeAttendance(IEnumerable<Attendance> records)
{
    if (ModelState.IsValid)
    {
        var newRecords = records.Select(x => new da.Attendance() { Id = x.RecordId, GroupId = x.GroupId, MemberId = x.MemberId, Date = x.Date });
        AttendanceRepository attendanceRepo = new AttendanceRepository();
        newRecords.Each(x => attendanceRepo.InsertOrUpdate(x));
        return RedirectToAction("Index");
    }
    else
    {
        return View();
    }

}

我们非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

您可以尝试将IList<Attendance> records传递给视图,然后按照以下方式操作:

for (int i = 0; i < Model.Count(); i++ )
{
    <tr>
        <td>@Html.DisplayFor(model => Model[i].MemberName)</td>
        <td>@Html.CheckBoxFor(model => Model[i].Present)</td>
        // ...
    </tr>                      
}

请务必更改@model IEnumerable<AT.Manager.Models.Attendance>以反映收集更改为IList