Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass List from Controller to View in MVC 3

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 one help me how to pass and how to access in View.

like image 817
Balu Avatar asked Jun 12 '12 10:06

Balu


People also ask

How do I pass model list from controller view?

You can use for this: 1 - Using View() , 2 - Using ViewData , 3 - Using ViewBag , 4 - Using your custom class , and 5 - Some combinations of those approaches.

How can we pass the data from controller to view in MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.


3 Answers

Passing data to view is simple as passing object to method. Take a look at Controller.View Method

protected internal ViewResult View(     Object model ) 

Something like this

//controller  List<MyObject> list = new List<MyObject>();  return View(list);   //view  @model List<MyObject>  // and property Model is type of List<MyObject>  @foreach(var item in Model) {     <span>@item.Name</span> } 
like image 181
archil Avatar answered Sep 24 '22 01:09

archil


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<abc.Models.Invoice>  @{     ViewBag.Title = "Invoices"; }  @{   var categories = (List<Category>) ViewData["MyData"]; // Cast the list }  @foreach (var c in @categories) // Print the list {   @Html.Label(c.Name); }  <table>     ...     @foreach (var item in Model)      {       ...     } </table> 

Hope it helps

like image 33
Nelson Miranda Avatar answered Sep 23 '22 01:09

Nelson Miranda


You can use the dynamic object ViewBag to pass data from Controllers to Views.

Add the following to your controller:

ViewBag.MyList = myList;

Then you can acces it from your view:

@ViewBag.MyList

// e.g.
@foreach (var item in ViewBag.MyList) { ... }
like image 23
Dennis Traub Avatar answered Sep 23 '22 01:09

Dennis Traub