我正在为 ASP MVC 使用包 BeginCollectionItem。我有一个要创建的表单和一个实体,它有一个 ICollection 属性。该属性需要在表单中动态填充项目。
这是 DTO 的外观:
public class WorkoutDTO
{
public int Id { get; set; }
//Some other properties
public ICollection <Exercise> Exercises { get; set; }
}
public class Exercise
{
public int ExerciseSelected { get; set; }
//Some other properties
}
这就是视图的样子:
@using (Html.BeginForm("Create", "Project", FormMethod.Post))
{
//Bunch of other inputs
@Html.Partial("_Exercise_Form", Model.Exercise_Create)
<input class="btn btn-action add-exercise-button" type="button" value="Add">
}
练习_表格部分视图:
@model TrackMe.Web.ViewModels.Workout_Create
@using (Html.BeginCollectionItem("Exercises"))
{
@Html.HiddenFor(m => m.Id)
@Html.DropDownListFor(m => m.ExerciseSelected, new SelectList(Model.Exercises, "Id", "Name"), "Exercise", new { @class = "form-control" })
@Html.TextBoxFor(m => m.Repetition1, new { @class = "form-control", placeholder = "Rep" })
@Html.TextBoxFor(m => m.Weight1, new { @class = "form-control", placeholder = "Kg" })
@Html.TextBoxFor(m => m.Repetition2, new { @class = "form-control", placeholder = "Rep" })
@Html.TextBoxFor(m => m.Weight2, new { @class = "form-control", placeholder = "Kg" })
@Html.TextBoxFor(m => m.Repetition3, new { @class = "form-control", placeholder = "Rep" })
@Html.TextBoxFor(m => m.Weight3, new { @class = "form-control", placeholder = "Kg" })
@Html.TextBoxFor(m => m.Repetition4, new { @class = "form-control", placeholder = "Rep" })
@Html.TextBoxFor(m => m.Weight4, new { @class = "form-control", placeholder = "Kg" })
@Html.TextBoxFor(m => m.Repetition5, new { @class = "form-control", placeholder = "Rep" })
@Html.TextBoxFor(m => m.Weight5, new { @class = "form-control", placeholder = "Kg" })
}
一切正常,当我发布 POST 时,我看到为集合中的每个项目分配了正确的索引:
Exercises.index:ae5247e5-b207-488d-84f9-3e2a9a8423ff
Exercises[ae5247e5-b207-488d-84f9-3e2a9a8423ff].Id:0
Exercises[ae5247e5-b207-488d-84f9-3e2a9a8423ff].ExerciseSelected:3
Exercises.index:352598b5-9264-4c8d-9501-ac5deb6e911d
Exercises[352598b5-9264-4c8d-9501-ac5deb6e911d].Id:0
Exercises[352598b5-9264-4c8d-9501-ac5deb6e911d].ExerciseSelected:3
Exercises.index:b64be97b-adbf-4d03-98d0-9d4f13d84ac6
Exercises[b64be97b-adbf-4d03-98d0-9d4f13d84ac6].Id:0
Exercises[b64be97b-adbf-4d03-98d0-9d4f13d84ac6].ExerciseSelected:6
问题是,有时,我的控制器中的一些练习集合的项目随机为 null:
[ResponseType(typeof(Workout))]
public IHttpActionResult Post(WorkoutDTO workoutDto)
{
var userId = User.Identity.GetUserId();
...
}
什么可能导致这种行为?我知道如果我使用带有整数索引的 for 循环它会带来这些问题,因为我可以打破顺序绑定,但这些是 GUID 对吗?
注意:我的 Model.Exercise_Create 视图模型与 DTO 看起来几乎相同。
更新:现在我看到唯一的空项目是具有以字母开头的 GUID 索引的项目。请参阅我发布的 FormData 以确认这一点:
1) Exercises.index:ae5247e5-b207-488d-84f9-3e2a9a8423ff --> NULL
2) Exercises.index:352598b5-9264-4c8d-9501-ac5deb6e911d --> NOT NULL
3) Exercises.index:b64be97b-adbf-4d03-98d0-9d4f13d84ac6 --> NULL
我没有实现任何自定义数据绑定,这很奇怪......