2011-03-24 64 views
1

所以我想呈現的局部視圖進入我的頁面,我得到了以下錯誤:問題有關模型錯誤被傳遞到局部視圖

錯誤

The model item passed into the dictionary is of type 
'System.Collections.Generic.List`1[GettingOrganized.Models.Todo]', but this 
dictionary requires a model item of type 'GettingOrganized.Models.Todo'. 

我不看看局部視圖或控制器出了什麼問題。

局部視圖

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<GettingOrganized.Models.Todo>" %> 
<% using (Html.BeginForm("Create", "Todo", FormMethod.Post, new {id="CreateTodo"})) {%> 

    <fieldset> 
     <legend>Fields</legend> 

     <div class="editor-label"> 
      <%= Html.LabelFor(model => model.Title) %> 
     </div> 
     <div class="editor-field"> 
      <%= Html.TextBoxFor(model => model.Title) %> 
      <%= Html.ValidationMessageFor(model => model.Title) %> 
     </div> 

     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 

<% } %> 

控制器索引視圖呈現局部視圖:

<% Html.RenderPartial("CreateElements"); %> 

有什麼想法?我想保持它接近這個設置,因爲它是強類型的。

UPDATE

因此提供了一些細節,現在這個問題正變得越來越清晰。我在div上的頁面上呈現視圖並隱藏它,用戶單擊某個鏈接。然後我想要顯示div。在「創建」視圖中使用此相同的部分,您可以在其中創建「待辦事項」。但我現在想在索引視圖中使用部分,它顯示了模型「Todo」的列表。

傳遞的模式,在「索引」的觀點:

Inherits="System.Web.Mvc.ViewPage<IEnumerable<GettingOrganized.Models.Todo>>" %> 

所以,如果我不想遍歷foreach循環,而只是想表明該模型的一個實例,誰做我這樣做?

而且我可以使用下面的視圖部分,它會工作,其帶走的強類型的模型:

WORKING局部

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
<% using (Html.BeginForm("Create", "Todo", 
FormMethod.Post, new { id="CreateTodo"})) {%> 
<fieldset> 
    <legend>Fields</legend> 
    <p> 
     <label for="Title">Title:</label> 
     <%=Html.TextBox("Title")%> 
     <%=Html.ValidationMessage("Title", "*")%> 
    </p> 
    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 
<p> 
<input type="submit" value="Create" /> 
</p> 
<% } %> 

可能的答案

但是,我相信我可能找到了答案。

<% Html.RenderPartial("CreateElements", new Todo()); %> 

這是處理這個問題的正確方法嗎?

+0

什麼是索引視圖模型? – BlackICE 2011-03-24 22:35:53

+0

我更新 - 根據「更新」與模型和更多信息 – pghtech 2011-03-25 16:29:47

回答

1

但是,我相信我可能已經找到了答案。

<% Html.RenderPartial("CreateElements", new Todo()); %> 
0

看起來你需要將模型傳遞到局部視圖 - 如:

<% Html.RenderPartial("CreateElements", myModel); %> 
+1

當!我無法編輯 - 我堅持在工作的IE6一半JS在這個網站上不起作用:(這是我要編輯:第二個想法...也許原來的模型通過到部分默認情況下(不能從我要測試的地方開發asp.net)。在這種情況下,我敢打賭你需要採用你的linq表達式並在最後添加.FirstOrDefault() - 只返回一個項目,而不是您目前用於模型的集合。 – jlnorsworthy 2011-03-24 22:09:56

0

我會去了解一下您是如何傳遞的模式進入的RenderPartial:

<% Html.RenderPartial("CreateElements", model); %> 

並確保該模型的類型爲GettingOrganized.Models.Todo。

0

由於您沒有將模型傳遞到RenderPartial調用中,因此MVC正在有效地嘗試使用父頁面中的ViewDataDictionary和模型爲您創建一個模型。

它看起來像父頁面有一個模型類型,這是一個List of ToDo項目,所以我想你可以在循環內調用你的RenderPartial方法;沿線的東西:

<% foreach (GettingOrganized.Models.Todo todoItem in Model) { 
    Html.RenderPartial("CreateElements", todoItem); 
} %>