ASP.net MVC4: Using a different model in a partial view?

99封情书 提交于 2019-12-01 16:19:27

Sure you can do that:

<% Html.Partial("_ListTodos", userTodos); %>

Pass the userTodos as a parameter to the Partial helper.

The error you're getting is because you're returning a list of todos to the Index page/view with return View(todos); inside the Index action method. The Index page needs a LoginModel object instead of an IEnumerable of todo objects.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<todo_moble_oauth.Models.LoginModel>" %>

To solve this, you need to change the way you're passing the todos though. Since your Index page receives a LoginModel, you can add a Todos property to this class like this:

[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; }

and then, modify your Index action method:

[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();
}

In the view, do this:

<% Html.Partial("_ListTodos", Model.Todos); %>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!