【问题标题】:IEnumerable<Twitter Status> View Output MVC 5IEnumerable<Twitter 状态> 查看输出 MVC 5
【发布时间】:2018-10-12 12:16:29
【问题描述】:

我正在尝试输出一组带有特定主题标签的推文。

我在控制器中有以下代码:

public ActionResult Test() {

        var service = new TwitterService("xxx", "xxx");
        service.AuthenticateWith("xxx", "xxx");

        var options = new SearchOptions { Q = "#test" };

        TwitterSearchResult tweets = service.Search(options);
        IEnumerable<TwitterStatus> status = tweets.Statuses;
        ViewBag.Tweets = status;


        //var tweets = service.Search(options);

        return View();
    }

我想在视图中输出 IEnumerable 中的结果。 但是我发现很难在视图中输出这些结果。有人可以帮忙吗?

【问题讨论】:

  • 你有什么问题(你甚至没有显示你查看代码)?
  • 我卡住了,我不知道我应该从哪里开始显示这个!
  • 首先删除 ViewBag.Tweets = status; 并使用 return View(status); 然后在视图中使用 @model IEnumerable&lt;TwitterStatus&gt; 并使用循环显示您想要的集合中每个项目的内容
  • 我认为使用 return View(status) 会导致一个只有 Twitter 提要的视图,对吧?我不希望我的视图只包含提要。
  • 然后创建一个包含IEnumerable&lt;TwitterStatus&gt; 属性的视图模型并将其传递给视图。你的问题既不清楚又太宽泛。您需要做一些研究以了解 MVC 的基础知识,并在遇到特定问题时回来

标签: asp.net-mvc twitter tweetsharp


【解决方案1】:

你的问题有点含糊,但我想我理解你的问题。

您需要通过您的操作将数据传递到您的视图中。

public ActionResult Test() {

    var service = new TwitterService("xxx", "xxx");
    service.AuthenticateWith("xxx", "xxx");

    var options = new SearchOptions { Q = "#test" };

    TwitterSearchResult tweets = service.Search(options);
    IEnumerable<TwitterStatus> status = tweets.Statuses;


    //var tweets = service.Search(options);

    return View(status);
}

请注意,我将状态对象传递到视图中。

现在在您看来,您可以绑定该对象。

@model IEnumerable<TwitterStatus>

@foreach(var status in Model){
    <div>
        @status.Id @*Id is an exmaple property. Use the actual properties inside "TwitterStatus"*@
    </div>
}

编辑:

如果您想在页面中包含多个内容,则必须使用部分视图。

您需要一个包含所有其他部分视图的视图。为此,只需为您的 twitter 信息定义一个操作,该操作将成为您的父视图。

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

那么你的剃须刀:

//AllInfo.cshtml
@Html.Action("Test", "YourController")

在 AllInfo.cshtml 中,我们在“YourController”中调用操作“Test”。我们将更改“Test”以返回 PartialView 而不是 View。

public ActionResult Test() {

    var service = new TwitterService("xxx", "xxx");
    service.AuthenticateWith("xxx", "xxx");

    var options = new SearchOptions { Q = "#test" };

    TwitterSearchResult tweets = service.Search(options);
    IEnumerable<TwitterStatus> status = tweets.Statuses;

    return PartialView(status);
}

局部视图的剃刀保持不变:

//Test.cshtml
@model IEnumerable<TwitterStatus>

@foreach(var status in Model){
    <div>
        @Model.Id @*Id is an exmaple property. Use the actual properties inside "TwitterStatus"
    </div>
}

您可以在 AllInfo.cshtml 页面中多次调用 @Html.Action() 并添加您需要的所有 PartialView。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2020-01-17
    • 2016-07-13
    相关资源
    最近更新 更多