我无法将完整的模型从我的视图返回到我的控制器
如果我使用下面的代码,我会将模型中的每个项目的IsSelected值返回到我的Action 但是,我得到了Thing对象的Null。
Thing对象是一个包含其他数据对象的大型数据对象
关于我哪里出错的任何想法?
我有以下代码;
@using (Html.BeginForm("myAction", "myController", FormMethod.Post))
{
<table class="table table-striped">
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Thing .CaseID)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Thing .Title)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().IsSelected)
</th>
</tr>
@for (int i = 0; i < Model.Count; i++)
{
@Html.Hidden("Thing.Index",i)
<tr>
<td>
@Html.DisplayFor(model => model[i].Thing.CaseNumber)
</td>
<td>
@Html.DisplayFor(model => model[i].Thing.CaseTitle)
</td>
<td>
@Html.CheckBoxFor(model => model[i].IsSelected)
</td>
</tr>
}
</table>
<input type="submit" name="SaveButton" value="Save" />
}
public ActionResult myAction(ICollection<SelectThingViewModel> caseViewModels)
{
return View("ShowFoundThings");
}
public class SelectThingViewModel
{
private bool _isSelected;
private Thing thing;
public SelectThingViewModel(Thing thing, bool isSelected)
{
this.IsSelected = isSelected;
this.thing= thing;
}
public SelectThingViewModel()
{
}
public Thing thing
{
get { return _thing; }
set { _case = value; }
}
[Display(Name = "Select")]
public bool IsSelected
{
get { return _isSelected; }
set { _isSelected = value; }
}
}
答案 0 :(得分:1)
提交时,DisplayFor不会返回值。您需要在<input>
中包含值...在您的情况下,您应该使用@Html.HiddenFor
<td>
@Html.DisplayFor(model => model[i].Case.CaseNumber)
@Hmlt.HiddenFor(model => model[i].Case.CaseNumber)
</td>
<td>
@Html.DisplayFor(model => model[i].Case.CaseTitle)
@Hmlt.HiddenFor(model => model[i].Case.CaseTitle)
</td>
<td>
@Html.CheckBoxFor(model => model[i].IsSelected)
</td>
默认情况下, @Html.DisplayFor()
只会向您的视图添加纯文本,因此<td>@Html.DisplayFor(model => model[i].Case.CaseNumber)</td>
的输出看起来像<td>12345</td>
,而值不在某些类型的输入字段中,值不会发布到您的行动。使用上面的代码会给你这样的东西
<td>
12345
<input name="[1].Case.CaseNumber" type="hidden" value="12345" />
</td>
输入的值已过帐,但在视图中不可见。