ASP.net MVC4:在partial view中使用不同的model?

8
我正在学习ASP.net MVC,如果我表达不清楚,请见谅。
在局部视图中使用与视图不同的模型是否可行?
我的视图Index当前继承了LoginModel,用于处理用户授权。一旦用户获得授权,我想让Index显示用户拥有的todos列表。todos通过LINQ检索。
因此,我的局部视图想要继承System.Web.Mvc.ViewPage<IEnumerable<todo_moble_oauth.Models.todo>>,但是当我使用它时会出现错误:`传递给字典的模型项的类型是

System.Data.Linq.DataQuery`1[todo_moble_oauth.Models.todo]', but this dictionary requires a model item of type 'todo_moble_oauth.Models.LoginModel'

这是我的索引视图。
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<todo_moble_oauth.Models.LoginModel>" %>

<section id="loginForm">
    <% if (Request.IsAuthenticated) { %>

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

    <% } else { %>

        <h1>Todo Mobile</h1>

        <blockquote>Easily store your list of todos using this simple mobile application</blockquote>

        <% using (Html.BeginForm()) { %>
            <%: Html.AntiForgeryToken() %>
            <%: Html.ValidationSummary(true) %>

                    <%: Html.LabelFor(m => m.UserName) %>
                    <p class="validation"><%: Html.ValidationMessageFor(m => m.UserName) %></p>
                    <%: Html.TextBoxFor(m => m.UserName) %>

                    <%: Html.LabelFor(m => m.Password) %>
                    <p class="validation"><%: Html.ValidationMessageFor(m => m.Password) %></p>
                    <%: Html.PasswordFor(m => m.Password) %>

                    <label class="checkbox" for="RememberMe">
                        <%: Html.CheckBoxFor(m => m.RememberMe) %>
                        Remember Me?
                    </label>

            <input type="submit" value="Login" />
        <% } %>
    <% } %>
</section>

我的部分视图_ListTodos如下:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<todo_moble_oauth.Models.todo>>" %>

<% foreach (var item in Model) { %>
      <%: Html.DisplayFor(modelItem => item.title) %>
      <%: Html.DisplayFor(modelItem => item.description) %>
<% } %>

我的LoginModel包含以下内容:

public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

HomeControllerIndex() 方法:

    [AllowAnonymous]
    public ActionResult Index()
    {
        // if user is logged in, show todo list
        if (Request.IsAuthenticated)
        {
            //var currentUser = Membership.GetUser().ProviderUserKey;
            todosDataContext objLinq = new todosDataContext();
            var todos = objLinq.todos.Select(x => x);
            return View(todos);
        }
        return View();
    }

任何帮助都非常感激,谢谢。
1个回答

6
当然,您可以这样做:
<% Html.Partial("_ListTodos", userTodos); %>

userTodos作为参数传递给Partial助手。
你得到的错误是因为在Index操作方法内部使用return View(todos);将待办事项列表返回给Index页面/视图。Index页面需要一个LoginModel对象,而不是一个待办事项对象的IEnumerable
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<todo_moble_oauth.Models.LoginModel>" %>

为解决这个问题,您需要改变传递“todos”的方式。由于您的“Index”页面接收了一个“LoginModel”,因此您可以像这样向该类添加一个“Todos”属性:
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }

[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }

public IEnumerable<todo_moble_oauth.Models.todo> Todos { get; set; }

接下来,修改您的 Index 操作方法:

[AllowAnonymous]
public ActionResult Index()
{
    // if user is logged in, show todo list
    if (Request.IsAuthenticated)
    {
        //var currentUser = Membership.GetUser().ProviderUserKey;
        todosDataContext objLinq = new todosDataContext();
        var todos = objLinq.todos.Select(x => x);

        LoginModel model = new LoginModel();
        model.Todos = todos;

        return View(model);
    }

    return View();
}

在视图中,执行以下操作:
<% Html.Partial("_ListTodos", Model.Todos); %>

2
非常感谢,这是一个不错且详细的解决方案。我不得不将 <% Html.Partial("_ListTodos", Model.Todos); %> 切换为 <% Html.RenderPartial("_ListTodos", Model.Todos); %> 才能使其正常工作,但现在一切都很完美,谢谢! - Neil
我曾经遇到过类似的情况,但我的模型结构略有不同,因此无需进行修改,只需要创建模型的新实例即可。为了满足我的需求,我使用了以下代码行(Razor 语法):@Html.Partial("dialogs/_partial-view", new MyObjectModel()) - BeanFlicker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接