简体   繁体   中英

2 controller and 1 view in ASP.NET MVC

I have 2 controllers, task and user.

I need to create a view for "create task to users". So I need "a user list" and "create task" view together.

Usually views inherit from only 1 class.

How can I create a view working with 2 classes?

Have any idea?

Your view can't and should not inherit from 2 classes.

Create a view model for your user which has a list of task view models.

You can implement each View (user list and create task) as partial views (.ascx user controls), and call each of these from within your View (.aspx page).

Rendering a partial view is done by using the RenderPartial method:

this.Html.RenderPartial("UserList");
this.Html.RenderPartial("CreateTask");

This will allow you to reuse and combine Views accross different Views (pages).

As AmisL points out, you can pass different parts of your ViewModel to each partial view.

A View can receive any class as Model, so just write a custom class, like:

public class UserListAndTasks
{
    public IQuerable<User> UserList;
    public Task Task;
}

Then, in your View, you can use partials:

<%= Html.RenderPartial("UserList", Model.UserList); %>
<%= Html.RenderPartial("CreateTask", Model.Task); %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM