简体   繁体   中英

How pass an object from controller to view with asp.net (motor aspx not razor)

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.

  • Create a class with Topics as name, and set public properties in the Topics class.
  • Create a strong type view with Topics as your model, within this view, you can display or edit your properties set in Topics class.
  • When you return a view back just return the model, in this case it will be return view (Topics).

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM