簡體   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