简体   繁体   中英

How to render a newsfeed in an asp.net mvc4 partial view

I have a new MVC4 project.

In my _Layout.cshtml I have the following:

<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>

My partial view is

<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 {id=@item.Id}, null)
    </div>    
}    

Is there a way I can make the partial view make the data call. Currently I have to do the following in my controller for every action:

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

I come unstuck where I already pass in a model to a view as I cannot then pass this into it as well.

I know I am doing something wrong, just not sure what or where.

I just want to be able to make a render call in my _layout and then the partial view to know to collect the data and then render itself. Or have I got the wrong end of the stick? I suppose I am trying to use it like an ascx...

You should switch from using a RenderPartial to a RenderAction . This allows you to go through the pipeline again and produce an ActionResult just like a partial, but with server side code. For example:

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

Then you make a NewsFeedController and provide an Index action method:

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);
     }
}

Then you simply have your CSHTML like a normal view in your Views/NewsFeed/Index.cshtml location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM