Home > DeveloperSection > Forums > Pass an object from controller to view with asp.net
Maria Susan

Total Post:29

Points:107
Posted on    January-29-2015 10:21 PM

 ASP.Net C#  ASP.NET MVC  View  Controller 
Ratings:


 1 Reply(s)
 649  View(s)
Rate this:

I need to pass an object from my controller to my view, I have the next code

public ActionResult General(int id)

    {

        List<Topics> topics = new List<Topics>();

        Topics top = new Topics();

        List<string> items = new List<string>();

        topics = top.getAllTopics(id);

        for (int i = 0; i < topics.Count; i++)

        {

 

            items.Add(topics[i].name);

 

        }

        ViewBag.Items = items;

        return View(topics.Count);

    }

and I need use the value of topics.Count in my view and putting it in a for.



sandy taylor
sandy taylor

Total Post:46

Points:324
Posted on    January-29-2015 10:43 PM

Try modifying your code to this

public ActionResult General(int id)

    {

        List<Topics> topics = new List<Topics>();

        Topics top = new Topics();

        List<string> items = new List<string>();

        topics = top.getAllTopics(id);

        for (int i = 0; i < topics.Count; i++)

        {

 

            items.Add(topics[i].name);

 

        }

        ViewBag.Items = items;

        ViewBag.Counter = topics.Count; // this line was added

        return View(topics.Count);

    }

And in your View add this if your are using Razor syntax

@for(var i=0;i<ViewBar.Counter;i++){

  //Do your logic here

 

}


Don't want to miss updates? Please click the below button!

Follow MindStick