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

您可能感兴趣的

HTML | Design Form What is HTML Form : HTML Form is a document which stores information of a user on a web server using interactive con...
html页面直接导出word pdf 直接上代码 html ///这里放想要导出的html 元素 function ExportWord() { var html = $("#div_workInfo").html(...
当Java遇见了Html–Jsp九大内置对象篇... jsp内置对象对象是web容器创建的一组对象,不使用new关键词久可以使用的内置对象。 九大内置对象包括以下: out –JspWriter request –ServletRequest ...
一个由line-height引发的血案与思考 最近UI走查,发现页面中所有包含文字区块的高度与设计稿中的高度完全不一致,然后UI妹子就爆炸了! 找了一下原因,发现是由于UI设计稿中设计的文字大部分是 font-size:24px;line-height:24px ,代码实现...
你可能从未听说过的15种HTML元素方法!... 初学者须知 我们来讨论HTML和DOM之间的区别。 显然,一个普通 元素就是HTML。您可以在.html的文件中使用它。它有一组 属性 影响它的外观和行为方式。这就是HTML,不过它与JavaScript无关。 DOM...