2011-02-18 80 views
1

我想呈現一個表,使用EditorFor和partialview,我想。ASP.Net MVC EditorFor不工作

我有一個模型與一個這樣定義一個列表<>屬性:

public List<TransactionSplitLine> TransactionSplitLines { get; set; } 

的想法是,用戶選擇幾個下拉菜單和輸入一個值到編輯框,點擊一個按鈕。該模型可以追溯到控制器,控制器會將輸入的值的列表<>

[HttpPost] 
public ActionResult AccountTransaction(AccountTransactionView model) 
{ 
    var reply = CreateModel(model); 
    if (model.CategoryIds != null) 
    { 
     foreach (var c in model.CategoryIds) 
     { 
      reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = int.Parse(c) }); 
     } 
    } 
    reply.TransactionSplitLines.Add(new TransactionSplitLine { Amount = "100", Category = "Test Category", SubCategory = "Test More", CategoryId = 1 }); 
    return View("AccountTransaction", reply); 
} 

忽略CreateModel。它只是設置一些數據。另外,我對數據進行了硬編碼。這最終將來自某些形式價值。

該模型然後返回到相同的屏幕,允許用戶輸入更多的數據。讀取列表<>中的任何項目並呈現表格。我還必須將當前的偵聽項目值存儲在隱藏字段中,以便可以將它們與輸入的新數據一起提交回來,以便每次用戶添加數據時都可以增加列表。

視圖的定義是這樣的:

<table width="600"> 
    <thead> 
     <tr class="headerRow"> 
      <td> 
       Category 
      </td> 
      <td> 
       Sub Category 
      </td> 
      <td> 
       Amount 
      </td> 
     </tr> 
    </thead> 
    <tbody> 
     <%=Html.EditorFor(m=>m.TransactionSplitLines) %> 
    </tbody> 
</table> 

這是我與EditorFor第一次嘗試......

我的觀點是在一個文件夾「視圖/的BankAccount/AccountTransaction.aspx

我已創建在一個視圖ASCX /共享/ TransactionSplitLines.ascx

用於ASCX的代碼是這樣的:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BudgieMoneySite.Models.TransactionSplitLine>" %> 


<tr> 
    <td> 
     <%=Model.Category %> 
     <%=Html.HiddenFor(x => x.CategoryId)%> 
    </td> 
    <td> 
     <%=Model.SubCategory %> 
     <%=Html.HiddenFor(x => x.SubCategoryId)%> 
    </td> 
    <td> 
     <%=Model.Amount %> 
     <%=Html.HiddenFor(x => x.AmountValue)%> 
    </td> 

</tr> 

這是數據

「這就是數據」只是測試的東西,這是從來沒有顯示。

當我運行此,所發生的一切是我的輸出呈現爲:

<table width="600"> 
    <thead> 
     <tr class="headerRow"> 

      <td> 
       Category 
      </td> 
      <td> 
       Sub Category 
      </td> 
      <td> 
       Amount 
      </td> 
     </tr> 

    </thead> 
    <tbody> 
     Test Category 
    </tbody> 
</table> 

這似乎是ASCX沒有被使用?我期望看到「這是數據」文本。但是,沒有。希望你能看到明顯的錯誤?

回答

6

你的編輯模板應該是:

~/Views/Shared/EditorTemplates/TransactionSplitLine.ascx 

或:

~/Views/BankAccount/EditorTemplates/TransactionSplitLine.ascx 

的ASCX的名字始終是集合項目的類型名稱(TransactionSplitLine而不是TransactionSplitLines),它應該位於~/Views/Shared/EditorTemplates~Views/ControllerName/EditorTemplates

或者,如果你想使用自定義編輯模板名稱:

<%= Html.EditorFor(m=>m.TransactionSplitLines, "~/Views/foo.ascx") %> 

或者在模型中使用UIHintAttribute

+0

謝謝@Darin Dimitrov!這解決了它。我修正了ASCX的名稱,它正在工作。謝謝。 – Craig 2011-02-19 00:08:32