2013-03-26 2 views
1

새로운 MVC4 프로젝트가 있습니다. 내 _Layout.cshtml에서asp.net mvc4 부분보기에서 뉴스 피드를 렌더링하는 방법

나는 다음과 같은 한 :

<div class="container maincontent"> 
     <div class="row"> 
      <div class="span2 hidden-phone"> 
       @* 
      In here is a RenderSection featured. This is declared in a section tag in Views\Home\Index.cshtml. 
      If this is static text for the whole site, don't render a section, just add it in. 
      You should also be able to use @Html.Partial("_LoginPartial") for example. 
      This _LoginPartial will need to be a cshtml in the Shared Views folder. 
      *@ 

       @{ Html.RenderPartial("_NewsFeed"); } 
      </div> 
      <div class="span10"> 
       @RenderBody() 
      </div> 
     </div> 
    </div> 

내 부분보기가

<div class="row newsfeed"> 
NEWS FEED 
@foreach (var item in ViewData["newsfeed"] as IEnumerable<NewsItem>) 
{ 
    <div class="span2 newsfeeditem"> 
     <h3>@item.NewsTitle</h3> 
     <p>@item.NewsContent</p> 
     @Html.ActionLink("More", "NewsItem", "News", new {[email protected]}, null) 
    </div>  
}  

이다 나는 부분보기는 데이터 통화를 할 수있는 방법이 있나요 . 현재 나는 모든 조치를 내 컨트롤러에서 다음을 수행해야합니다 :

ViewData["newsfeed"] = _db.NewsItems.OrderByDescending(u => u.DateAdded).Where(u => u.IsLive == true).Take(4); 
     return View(ViewData); 

나는 다음뿐만 아니라 그것으로이 통과 할 수없는 나는 이미 뷰에 모델로 전달 곳에 떨어진 온다.

나는 무엇이 잘못되었는지를 알고 있으며, 무엇이 어디서 확실하지 않습니다.

내 _layout에서 부분적으로 렌더링을 호출하여 데이터를 수집 한 다음 렌더링 할 수 있기를 바랍니다. 아니면 막대기의 끝 부분을 잘못 잡았습니까? 나는 그것을 ascx와 같이 사용하려한다고 가정합니다 ...

답변

2

RenderPartial에서 RenderAction으로 전환해야합니다. 이렇게하면 파이프 라인을 다시 거쳐 부분적으로 동작하는 것처럼 ActionResult를 생성 할 수 있지만 서버 측 코드로 생성 할 수 있습니다. 예를 들어 :

@Html.RenderAction("Index", "NewsFeed"); 

그런 다음 당신은 NewsFeedController을하고 Index 액션 메소드 제공 :
public class NewsFeedController : Controller 
{ 
    public ActionResult Index() 
    { 
      var modelData = _db.NewsItems.OrderByDescending(...); 
      // Hook up or initialize _db here however you normally are doing it 

      return PartialView(modelData); 
    } 
} 

그런 다음 당신은 단순히 당신의 조회수/뉴스 피드/Index.cshtml 위치에서 일반보기처럼 CSHTML을 가지고 있습니다.

+0

정확히 내가 필요한 것. 건배 –