繁体   English   中英

从视图返回填充列表的强类型列表?

[英]Strongly typed list return from View to fill Model?

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

总体目标是这样的:

  • 索引:所有员工的复选框列表。 表中的组,由工作地址分隔(可通过foreach(字符串地址)+ foreach(雇员e轻松地实现,其中e.Where(地址)有点神奇)。

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

  • 完成并显示。 此部分应将数据插入数据库并呈现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" />  
}

我期望它返回上面的模型。 而是返回一个空的Employee列表。 我确定我缺少一些愚蠢的东西,但我不明白是什么。

接收端的控制器如下所示:

    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();
    }

我怀疑我无法掌握的是如何在视图中创建一个Employee,以使其填充强类型列表。 还是我完全误解了这些概念?

我可以轻松地传递简单的数据,因此它似乎完全围绕列表而行,但是当我得到该列表时,该列表为空,但是我的Google-fu令我失望了,因此,我恳请同胞为您寻求帮助。

我相信要在模型绑定期间合并实体列表,需要在实体的属性名称之前添加索引,如下所示:

@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列表的方式。

注意:此处的modelIndexModel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM