asp.net MVC Database call in partial view

感情迁移 提交于 2020-12-13 18:34:17

问题


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

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