如何用asp.net传递一个对象从控制器到视图(马达aspx不是剃刀)

本文关键字:马达 视图 aspx 剃刀 控制器 net asp 何用 一个对象 | 更新日期: 2023-09-27 18:05:08

我需要将一个对象从控制器传递到视图,我有下一个代码

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

,我需要在我的视图中使用topics.Count的值,并将其放在for中

如何用asp.net传递一个对象从控制器到视图(马达aspx不是剃刀)

试着这样修改你的代码

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

如果使用Razor语法,在View中添加

@for(var i=0;i<ViewBar.Counter;i++){
  //Do your logic here
}
  • 创建一个名为Topics的类,并在类中设置公共属性主题类。
  • 创建一个强类型视图,将Topics作为您的模型视图,您可以在Topics类中显示或编辑您的属性集。
  • 当你返回一个视图返回模型,在这个例子中它将返回视图(主题)。