0

我正在尝试传递数据,但在处理强类型数据时遇到问题。

总体目标是这样的:

  • 索引:所有员工的复选框列表。表中的组,由工作地址分隔(通过 foreach(string address) + foreach(Employee e where e.Where(address) 很容易做到这一点很神奇。

  • 报告的详细信息。这部分应该显示选择的用户列表,询问几个小时和一个标题。很简单。

  • 完成并显示。这部分应该将数据插入数据库并呈现 pdf。

这是我希望员工数据所在的类。为了缩短它,我删除了其中的方法:

public class IndexModel
{
    public List<EmployeeForList> Employees { get; set; }

    public class EmployeeForList
    {
        public bool IsChecked { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int EmployeeId { get; set; }
        public string Building { get; set; }

        public EmployeeForList()
        {
        }

        public EmployeeForList(TXEP.InfoWeb employee)
        {

            this.FirstName = employee.FirstName;
            this.IsChecked = false;
            this.LastName = employee.LastName;
            this.Building = employee.BuildingAddress;
            this.EmployeeId = employee.EmployeeId;
        }
    }
}

这是查看代码:

@using (@Html.BeginForm("TrainingDetail", "Home", FormMethod.Post))
{
<table border="1">
    @foreach (string building in Model.GetUniqueBuildings())
    {
        <tr>
        @foreach (var employee in Model.GetEmployeesFromBuilding(building))
        {
            <td>
                @Html.CheckBoxFor(model => @Model.GetEmployee(employee).IsChecked)
                @Html.HiddenFor(model => @Model.GetEmployee(employee).LastName)
                @Html.HiddenFor(model => @Model.GetEmployee(employee).FirstName)
                @Html.HiddenFor(model => @Model.GetEmployee(employee).EmployeeId)
                @Html.HiddenFor(model => @Model.GetEmployee(employee).Building)
                @employee.LastName, @employee.FirstName
            </td>
        }
        </tr>
    }
</table>
    <input type="submit" value="sub" />  
}

我期待它返回上面的模型。相反,它返回一个空的员工列表。我确定我错过了一些愚蠢的东西,但我不明白是什么。

接收端的 Controller 如下所示:

    public ActionResult TrainingDetail(Models.IndexModel indexModel)
    {
        if (indexModel.Employees == null)
        {
            ViewBag.Message = "EMPTY FOO";
            return View();
        }
        int count = indexModel.Employees.Where(x => x.IsChecked == true).Count();
        ViewBag.Message = count.ToString();

        return View();
    }

我怀疑我没有掌握的是如何在视图中创建一个员工,以便它填充一个强类型列表。还是我完全误解了这些概念?

它似乎完全围绕着成为一个列表,因为我可以轻松地传递简单的数据——但是当我得到它时这个列表是空的,但是我的 Google-fu 让我失望了,所以我恳求你们,我的兄弟们,寻求帮助。

4

1 回答 1

3

我相信在模型绑定期间要对实体列表进行水合,实体属性的名称需要以如下索引作为前缀:

@Html.CheckBoxFor(model => model.Employees[0].IsChecked)
@Html.HiddenFor(model => model.Employees[0].LastName)
@Html.HiddenFor(model => model.Employees[0].FirstName)
@Html.HiddenFor(model => model.Employees[0].EmployeeId)
@Html.HiddenFor(model => model.Employees[0].Building)

这就是 MVC 知道如何创建新EmployeeForList实体并将其添加到Employees列表中的方式。

注意: model这里是IndexModel.

于 2013-08-23T13:29:52.357 回答