2011-04-14 49 views
0

我有一個列表對象,我試圖在foreach循環中顯示文本框。但是,該帖子返回空對象。我看不出原因。在foreach循環中輸入表單返回空模型

這裏是在視圖的代碼

使用(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> 

<%}%>

這裏是控制器

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

,能不能請您編輯的代碼部分。 – 2011-04-14 07:54:00

+0

請考慮灰色框上方的行,作爲代碼的一部分。 – merawi 2011-04-14 09:08:21

回答

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) 
     { 
      ... 
     } 
    } 
    ... 
} 
+0

Darin,我在用戶控件上使用了這個: – merawi 2011-04-14 10:35:18

+0

這很有幫助,非常感謝。 – merawi 2011-04-14 11:54:18