IEnumerable<Twitter Status> View Output MVC 5

80 Views Asked by At

I am trying to output a set of tweets with a certain hashtag.

I have the following code in the controller:

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

I want to output the results that are in the IEnumerable in a view. But I am finding it difficult to output these results in a view. Can anyone help please?

1

There are 1 best solutions below

0
Kevin Suarez On

Your question is a bit vague but I think I understand your problem.

You'll want to pass the data into your view from your action.

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

Notice I pass in the status object into the view.

Now in your view you can just bind that object.

@model IEnumerable<TwitterStatus>

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

Edit:

If you want to have multiple things inside your page you'll have to use Partial Views.

You'll need a view that will encompass all your other partial views. To do this, just define a action for your twitter info that will be your parent view.

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

Then your razor:

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

In AllInfo.cshtml we call the action "Test" inside "YourController". We'll change "Test" to return a PartialView instead of a 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);
}

The razor stays the same for your partial view:

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

You can call @Html.Action() as many times as you want in your AllInfo.cshtml page and add all the PartialViews you need.