JKu*_*ufa 6 c# model-view-controller asp.net-mvc viewmodel razor
I am trying to pass a view model with complex types to my controller. I have researched everything I can top to bottom over this subject and I am still confused.
The Problem:
When I click my submit button, the view model is passed in but the List of MacroInfo property is null.
UpdateIndexViewModel
public class UpdateIndexViewModel
{
//This view model will become larger later
public List<MacroInfo> MacrosToUpdate { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
MacroInfo
public class MacroInfo
{
public bool IsSelected { get; set; }
public string FullPath { get; set; }
public string Id { get; set; }
public DateTime CreatedAt { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
Controller Action
[HttpPost]
public ActionResult Submit(UpdateIndexViewModel updateIndexViewModel)
{
//updateIndexViewModel.MacrosToUpdate is null ??
}
Run Code Online (Sandbox Code Playgroud)
Index View
@model EplanInterface.Core.ViewModels.UpdateIndexViewModel
@using (Html.BeginForm("Submit", "Update", FormMethod.Post))
{
<table style="width:100%" , class="table-bordered">
<thead>
<tr>
<th>#</th>
<th>Macro Path</th>
<th>Created At</th>
<th>Update</th>
</tr>
</thead>
@for (int i = 1; i < Model.MacrosToUpdate.Count; i++)
{
<tr>
<td>@Html.TextBoxFor(m =>Model.MacrosToUpdate[i].FullPath)</td>
<td>@Html.TextBoxFor(m => Model.MacrosToUpdate[i].CreatedAt)</td>
<td>@Html.CheckBoxFor(b => Model.MacrosToUpdate[i].IsSelected)</td>
</tr>
}
</table>
<input type="submit" class="btn btn-primary" value="Submit"/>
}
Run Code Online (Sandbox Code Playgroud)
What I have tried
I tried changing the controller actions property being passed in to List<MacroInfo> macrosToUpdate, but when doing this the property is still null.
Chrome network inspection
Final Remarks
I am not sure if I need to be using an AJAX post to do this, or if my variable names just are not formatted correctly. I am pretty sure it is a binding issue I am not understanding.
If anyone could point me in the right direction I would really appreciate it.
你的模板的这一部分有点错误。
@for (int i = 1; i < Model.MacrosToUpdate.Count; i++)
{
<tr>
<td>@Html.TextBoxFor(m =>Model.MacrosToUpdate[i].FullPath)</td>
<td>@Html.TextBoxFor(m => Model.MacrosToUpdate[i].CreatedAt)</td>
<td>@Html.CheckBoxFor(b => Model.MacrosToUpdate[i].IsSelected)</td>
</tr>
}
Run Code Online (Sandbox Code Playgroud)
请更改以下内容并重试。
@for (int i = 0; i < Model.MacrosToUpdate.Count;
{
<tr>
<td>@i</td>
<td>@Html.TextBoxFor(m => m.MacrosToUpdate[i].FullPath)</td>
<td>@Html.TextBoxFor(m => m.MacrosToUpdate[i].CreatedAt)</td>
<td>@Html.CheckBoxFor(b => b.MacrosToUpdate[i].IsSelected)</td>
</tr>
}
Run Code Online (Sandbox Code Playgroud)
首先,您以 1 开始循环,这是根本原因。由于缺少第零个索引,模型绑定器无法正确绑定列表。
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |