如何在cshtml

时间:2017-11-04 02:35:54

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我正在一个mvc项目中使用asp.net core 2.0。我有一个名为Compra的班级,其中包含Combos列表。我的问题是,如何列出所有组合并将其显示给用户?

“Compra”类的代码是:

public class Compra
{
    public int ID { get; set; }
    List<Combo> Compras = new List<Combo>()
}

我想向用户显示的视图是cshtml,如果可能,我希望它显示如下:

Compra

选定组合

        
  1. 元素1
  2.     
  3. 元素2
  4.     
  5. 元素3
  6.     
  7. 元素4
  8.     
  9. 元素5
  10. 先谢谢大卫。

3 个答案:

答案 0 :(得分:0)

这是你可以做的例子..

     // class
     public class Compra
      {
        public int ID { get; set; }
        List<Combo> compras = new List<Combo>();
      }
     public class Combo
      {
        public int id{ get; set; } 
        public string Name { get; set; }
      } 

    // view
    @model Compra

      <ol>
        @foreach (var item in Model.compras)
         {
          <li>
              @item.Name
          </li>
         }
     </ol>

答案 1 :(得分:0)

试试这个。假设Title类具有@model Compra @{ ViewBag.Title = "Page title" } <h2>Compra</h2> <h3>Selected Combos</h3> @foreach (var combo in Model.Compras){ <ol> <li> @combo.Title </li> </ol> } 作为其属性之一。

convert.exe -verbose -density 600 +antialias "E:\sample pdf\sample50 B.pdf" -quality 100 "D:\sample50_2.png"

答案 2 :(得分:0)

使用View-bag而不是使用模型

查看页面.cshtml

@{
    ViewBag.Title = "Compra";
}
<h2>Compra</h2>
<h3>Selected Combos</h3>
@if (ViewBag.compra != null)
{
    <ol>
        @foreach (var compra in ViewBag.compra.ComboList)
        {
            <li>
                @compra.NAME
            </li>
        }
    </ol>
}

控制器 - 操作方法 --Bind Compra Class

public ActionResult Index()
        {
            Compra compra = new Compra();
            compra.ID = "1";
            compra.ComboList.Add(new Combo { ID = "1", NAME = "Element 1" });
            compra.ComboList.Add(new Combo { ID = "2", NAME = "Element 2" });
            compra.ComboList.Add(new Combo { ID = "3", NAME = "Element 3" });
            compra.ComboList.Add(new Combo { ID = "3", NAME = "Element 4" });
            compra.ComboList.Add(new Combo { ID = "3", NAME = "Element 5" });
            ViewBag.compra = compra;

            return View();
        }

这里是你的类结构

public class Compra
    {
        public Compra()
        {
            ComboList = new List<Combo>();
        }
        public string ID { set; get; }
        public List<Combo> ComboList { set; get; }
    }

    public class Combo
    {
        public string ID { set; get; }
        public string NAME { set; get; }
    }

Output