Iterate through html.action result

综合技术 2018-01-31 阅读原文

I have the following ActionResult method in my Controller Class which returns posts:

public ActionResult Feed()
{
    List posts = getPosts();
    return PartialView(posts);
}

How do I iterate trough these results (creating a new div for each post). I tried @foreach (var item in Html.Action("Feed")) but this didn't work.

Update 3:

Here is all relevant code to this problem. I also stopt using a model for the posts and now directly use the LinqToTwitter.Status object.

FeedController.cs

public ActionResult Index()
    {
        return View();
    }

    public ActionResult Feed()
    {
        return PartialView(GetStatuses());
    }

    private List GetStatuses()
    {
        //Code to get tweets
    }

Index.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Feed";
}

@{ Html.Action("Feed"); }

Feed.cshtml

@model List

@foreach (var item in Model) {
@*More divs for design*@
}

Exception thrown on Html.Action("Feed"); in Index.cshtml:

And corresponding webresult:

your code @foreach (var item in Html.Action("Feed")) does not work the way you think it should.

Html.Action("Feed") will execute a ActionResult which can return a View (HTML), JSON, File etc etc... In your case it returns a PartialView meaning it returns you an HTML.

So how you code this is. In your main view add a this line of code where you want your divs.

@Html.Action("Feed")

Then with your current ActionResult as is

public ActionResult Feed()
{
    List posts = getPosts();
    return PartialView(posts);
}

Add a new partial viewinto your project solution. This partial view must intake a List type model and then loop it.

Your Partial view name should be Feed and its content as below.

@model List

@foreach (var post in Model){
  //post will be a instance of each Post object.
  

post.Header

// just an example
}
Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!