Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the controller pass information between the model and the view?

Tags:

asp.net-mvc

In ASP.NET MVC, how does the controller pass information between the model and the view?

Let's say I have a list of baseball players in my database. After I query those players using LINQ in the controller, how do I then pass this information on to view (my list of baseball players and their stats)?

And after I pass them onto the view, how do I use the inline code in the views html to loop through and display it?

like image 670
Fatal510 Avatar asked Dec 31 '25 22:12

Fatal510


2 Answers

The controller has a ViewData field that you can use. It's a dictionary and you can use like that:

ViewData["players"] = yourList;

After that you can access the same ViewData on the View:

<? foreach(var player in ViewData["players"] as List) {} ?>

You can also make a strong typed view, changing the view base class from ViewPage to ViewPage < T >, where T is your user-defined class. At the controller you return the class on the return method View() and access it on the view using the ViewModel property.

like image 155
Edwin Jarvis Avatar answered Jan 07 '26 05:01

Edwin Jarvis


Check out the ASP.NET MVC Tutorials at http://www.asp.net/learn/mvc/, in particular the first 3 tutorials on Models, Controllers and Views, and how they interact.

like image 23
JMS Avatar answered Jan 07 '26 06:01

JMS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!