问题
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>();
}
%>
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/1908242/asp-net-mvc-database-call-in-partial-view