2012-02-22 43 views
-1

我有一個MVC2視圖至極強烈綁定到一個模型......如何在foreach循環中綁定Ienumerable <TModel>?

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.IEnumerable<AdjustmentModel>>" %> 

並在視圖我有...

  foreach (var adjustment in Model) 
      {%> 
     <tr row="<%: row %>"> 
      <td class="nonSelectable" column="0"> 
       <div> 
        ...I want to put a textbox here that has name="someId" 
        and val="someVal" but how? 
       </div> 
      </td> 

      }%> 

該模型是

class AdjustmentModel 
{ 
    public int ID; 
    public int amount; 
} 

我只是不能確定我傳遞給Html.TextBoxFor()的委託,因爲當我傳遞一個模型時,智能感知不會像im傳遞一個Ienumerable那樣工作,那麼如何使用該模型?

回答

1

我會推薦你​​使用編輯器模板。這樣,您就不需要寫任何循環,仍然保持了強勁的打字:

<table> 
    <%= Html.EditorForModel() %> 
</table> 

,然後定義將被自動呈現您的收藏中的每個元素(~/Views/Shared/EditorTemplates/AdjustmentModel.ascx)編輯模板:

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<AdjustmentModel>" 
%> 
<tr> 
    <td class="nonSelectable" column="0"> 
     <div> 
      <%= Html.HiddenFor(x => x.ID) %> 
      <%= Html.EditorFor(x => x.amount) %> 
     </div> 
    </td> 
</tr> 

重要的是尊重在~/Views/CurrentController/EditorTemplates~/Views/Shared/EditorTemplates文件夾中找到您的編輯器模板的約定。模板的名稱必須是集合中使用的類型。因此,例如,如果您有IEnumerable<AdjustmentModel>,則該文件必須被稱爲AdjustmentModel.ascx,並且顯然強類型爲AdjustmentModel。然後這個模板將被自動調用每個元素。

0

你可以使用Html.TextBox

<%= Html.TextBox("SomeId", "SomeVal") %>