如何捕获Controller类中嵌入到模型中的列表

我有一个名为HomeViewModel的视图模型。我也有另一个viewmodel TaskViewModel。我已经将TaskViewModel作为IList包含在HomeViewModel中

public class HomeViewModel
{
    public IList<TaskViewModel> myTaskList {get; set;}
}

在视图中,我使用以下代码从用户捕获数据:

@model My.ViewModels.HomeViewModel

                                    <div>
                                        @Html.EditorFor(model => model.myTaskList[0].Description)
                                        @Html.EditorFor(model => model.myTaskList[0].Hours)

                                        <button onclick="showTheRepeatedFields() ">Add Task</button>
                                    </div>

在控制器中,我收到了“ HomeViewModel”的所有其他参数,但没有收到IList。 控制器如下:

public JsonResult SaveWork(int Supervisor, DateTime In, DateTime Out, int Employee, string Description, IList<TaskViewModel> myTaskList)

当我点击debug时,方法签名中的myTaskList为空。可能是什么问题

评论
  • 神经
    神经 回复

    You should try putting your list generation inside a for loop:

    <div>
        @for (var i = 0; i < model.myTaskList.Count; i++) 
        {
            @Html.EditorFor(model => model.myTaskList[i].Description)
            @Html.EditorFor(model => model.myTaskList[i].Hours)
        }
        <button onclick="showTheRepeatedFields() ">Add Task</button>
    </div>
    

    I know that it makes no sense if you already knows that your myTaskList collection will have always one element, but with the for loop ASP.Net is able to generate the form's elements in a way that allows it to manage the model binding to be able to populate the variables in the controller's method.