How to pass List from Controller to View in MVC 3

后端 未结 4 943
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 15:17

I have a List<> binded with some data in Controller action and I want to pass that List<> to View to bind with DataGrid in Razor View.

I am new to MVC.Can any

4条回答
  •  囚心锁ツ
    2020-12-14 16:02

    I did this;

    In controller:

    public ActionResult Index()
    {
      var invoices = db.Invoices;
    
      var categories = db.Categories.ToList();
      ViewData["MyData"] = categories; // Send this list to the view
    
      return View(invoices.ToList());
    }
    

    In view:

    @model IEnumerable
    
    @{
        ViewBag.Title = "Invoices";
    }
    
    @{
      var categories = (List) ViewData["MyData"]; // Cast the list
    }
    
    @foreach (var c in @categories) // Print the list
    {
      @Html.Label(c.Name);
    }
    
    
        ...
        @foreach (var item in Model) 
        {
          ...
        }
    

    Hope it helps

提交回复
热议问题