views:

78

answers:

2

I would like to make a database call in a partial view in asp.net MVC. I am not sure how to actually go about that. I am trying to get an instance of the repository so I can make a couple calls to the DB to build some info on the page. Not sure if I am even close but does anyone have any ideas ?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>



<%
    if (Request.IsAuthenticated)
    {
        var repos = MyMVC.Models.Repository.IRepository<UserProfile>();

    }
%>
+4  A: 

You're attempting to violate the principals of the Model-View-Controller architecture.

The proper way to implement this would be to make a Partial View and allow your Controller to get the data...then pass it to the Partial View for rendering.

Justin Niessner
Yes, I'm sorry I meant a partial view.
gmcalab
Even so, a Partial View should not have data retreival logic in it. A View (even a partial) should only be responsible for rendering the data given to it.
Justin Niessner
A: 

Try using MvcContrib. Check out the RenderAction method. It lets you keep the data access in the controller, and the view stuff in the view, without mixing the responsibilities.

<div id="some-partial-container">
    <% Html.RenderAction<MyController>(c => c.SomeAction()); %>
</div>

Also, RenderAction will be in MVC 2, which makes me very happy. It won't support a generic implementation, though (when I last checked).

<div id="some-partial-container">
    <% Html.RenderAction("SomeAction", "MyController"); %>
</div>

Phil Haack on RenderAction: http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx

Jarrett Meyer