views:

316

answers:

2

Is it possible that two different views use the same controller? I have very complex controller that displays some data. Now I need to display this data (which is retrieved using ajax) in two partial views because I want to place them on different positions in layout.

+2  A: 

the View() function can be passed arguments, for instance:

return View(); // The view with the same name as the action.
return View("MyView") // The view named "MyView"

There are a few more overloads too. Does this fit the bill?

If not, why not partial views, for instance, given this model:

public class BlogItem
{
    public string Title { get; set; }
    public int Id { get; set; }
}

And this action:

public ActionResult Index()
{
    var items = new List<BlogItem>
                {
                    new BlogItem { Title = "Test Blog Item", Id = 1 }
                };
    return View(items);
}

And this view:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<BlogItem>>" %>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
    <% Html.RenderPartial("List", Model); %>

    <% Html.RenderPartial("Icon", Model); %>
</asp:Content>

I can have two partial views using the same model:

List:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<BlogItem>" %>
<ul>
    <% foreach (var item in Model) { %>
        <li><%= item.Title %></li>
    <% } %>
</ul>

Icon:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<BlogItem>" %>
<div>
    <% foreach (var item in Model) { %>
        <div class="icon"><img src="..." /></div>
        <div class="text"><%= item.Title %></div>
    <% } %>
</div>

Would that work?

Matthew Abbott
I can't have return two times at once in controller?
ile
@ile: No, but you can use conditional logic in each action method and choose your views accordingly. Or use a generic view and pass it some template to be parsed (though that's a bit more advanced).
Simon
What conditional logic? I need controller to pass data to two views at the SAME TIME. That is not possible?
ile
@ile - You may want make your controller action simpler and split it up so that you can serve two views.
Ahmad
@Ahmad - the problem is that both views depend on identical data. I think I'll have to use jquery to parse reponse data.Thanks anyway
ile
Would partial views not work? I've updated the example
Matthew Abbott
A: 

Based on my understanding so far, you want one controller action to return two views. I somehow think that this is not possible.

You have mentioned that the views are used to display identical data is different ways. My suggestion would to return a JsonResult from the controller action and build the view client side.

Ahmad
oops - based on your comment which I have now read correctly, you may be doing this after all.
Ahmad