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!阅读原文】。感谢您的支持!

您可能感兴趣的

Is there a way to change the width of the & lt... I've noticed that any modification of the 's style with respect to its width doesn't have any effect. It's seems to always be set to "auto". ...
I need a div to fill from the right of a 0 auto ma... I have a main content div that is 950px and has 0 auto margins so it's centered. It has transparent content in it so can't have a background color but...
Error with retrieving the value from the html chec... In my html I have: No B C No F NC No RRI kept the first checkbox checked by default. I want to access the value of the checkbox ...
Extra lines appear in a button when border radius ... -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-right-colors: none; -moz-border-top-colors: none; border-color: -moz...
How do I stop text from showing / flowing outside ... I'm not sure why, but I get this text showing / flowing outside of the tag. I thought it was something to do with floats, but I have tr...