我有一个列表对象,我尝试在foreach循环中显示文本框。但是帖子返回空对象。我看不出原因。
以下是视图中的代码
<%using(Html.BeginForm(“makeTransfer”,“shareTransfer”)){%>
<% foreach (var i in Model.Inform)//int i = 0; i < Model.Inform.Count(); i++){ %>
<%:Html.HiddenFor(x=>i.shares, new{@value = i.shares}) %>
...
<td style = "width:20px"><%:Html.TextBoxFor(x=>i.sharesRq)%></td> cuddling
<%} %>
<%:Html.HiddenFor(x => x.accSrc, new { @value = Model.accSrc })%>
<%:Html.HiddenFor(x=>x.accDst, new{ @value = Model.accDst}) %>
Date of Transfer<%:Html.TextBoxFor(x => x.date)%>
Transfer with benefit<%:Html.CheckBoxFor(x => x.withBenefit)%>
<input type="submit" name="save" value="Save" /></div>
<input type="submit" name="cancel" value="Cancel" /></div>
&lt;%}%&gt;
这是控制器
public ActionResult makeTransfer(vmTransfer transfer,string save,string cancel) {
if (cancel != null)
return RedirectToAction("startTransfer");
else if (save != null)
{
foreach (var t in transfer.Inform)
{ ...
我的问题是,当表单发布时,transfer.Inform(从最后一行开始的第二行)是一个列表是空的。请尽快提供帮助。
答案 0 :(得分:1)
我建议您使用编辑器模板,而不是在视图中编写任何循环:
<% using (Html.BeginForm("makeTransfer", "shareTransfer")) { %>
<%= Html.EditorFor(x => x.Inform) %>
<%= Html.HiddenFor(x => x.accSrc, new { @value = Model.accSrc }) %>
<%= Html.HiddenFor(x => x.accDst, new { @value = Model.accDst }) %>
Date of Transfer <%= Html.TextBoxFor(x => x.date) %>
Transfer with benefit <%= Html.CheckBoxFor(x => x.withBenefit) %>
<input type="submit" name="save" value="Save" /></div>
<input type="submit" name="cancel" value="Cancel" /></div>
<% } %>
并在相应的编辑器模板(~/Views/Shared/EditorTemplates/InformViewModel.ascx
)中:
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.InformViewModel>"
%>
<%= Html.HiddenFor(x => x.shares) %>
...
<td style="width:20px">
<%= Html.TextBoxFor(x => x.sharesRq) %>
</td>
备注:您可能需要根据Inform
属性的类型调整编辑器模板的名称。
编辑器模板将负责生成输入字段的正确ID和名称,以便一切正确绑定:
[HttpPost]
public ActionResult makeTransfer(vmTransfer transfer, string save, string cancel)
{
if (cancel != null)
{
return RedirectToAction("startTransfer");
}
else if (save != null)
{
foreach (var t in transfer.Inform)
{
...
}
}
...
}