关于模型传递到局部视图的错误问题

时间:2011-03-24 22:01:01

标签: asp.net-mvc

所以我试图将部分视图呈现到我的页面中,我收到以下错误:

错误

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'.

我看不出部分视图或控制器有什么问题。

PARTIAL VIEW

<%@ 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"); %> 

有什么想法?我想保持它接近这个设置,因为是强类型。

更新

因此,为了提供更多细节,现在问题变得越来越清晰。我正在div中的页面上呈现视图,并隐藏用户单击某个链接。然后我想展示div。在“创建”视图中使用相同的部分,您可以在其中创建“待办事项”。但我现在想在Index视图中使用partial来显示模型“Todo”的列表。

模型在“索引”视图中传入:

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

因此,如果我不想循环遍历foreach循环,并且只想显示模型的一个实例,我该怎么做?

此外,我可以使用以下视图进行局部操作,它可以将强类型转换为模型:

部分工作

<%@ 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()); %>

这是处理此问题的正确方法吗?

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

看起来你需要将模型传递给局部视图 - 如:

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

答案 2 :(得分:0)

我会研究你如何将你的模型传递到RenderPartial:

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

并确保该模型的类型为GettingOrganized.Models.Todo。

答案 3 :(得分:0)

由于您没有将模型传递给RenderPartial调用,因此MVC正在尝试使用父页面中的ViewDataDictionary和模型为您创建一个模型。

看起来父页面的模型类型是ToDo项目列表,所以我猜你可以在循环中调用你的RenderPartial方法;类似的东西:

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