How to Pass Data from Controller to View ASP.NET MVC ??
- The MVC pattern stands for [ Model, View and Controller ]. So, Model, View and Controller all distinct and separate but all work together to build MVC Applications.
- The controller coordinate model and views to execute the application logic. The view display the data to the client.
- There are two ways to pass the data from controller to view.
1. ViewData.
2. ViewBag.
- Lets Create New ASP.Net MVC Application with Basic Template and Name it to “ViewBagDemo”.
- Now, Add HomeController inside controller folder and add Index action as shown in below code.
Code :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Name = "Manav Pandya";
ViewBag.Description = "This is the Demo of ViewBag in ASP.NET MVC";
return View();
}
}
- Now, right click on Index action -> Add View -> Leave all configuration -> click “Add”.
- Now, add below line of code into Index.cshtml view to access ViewBag property in the view.
Code :
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<h1>@ViewBag.Name</h1>
<div>@ViewBag.Description</div>
Now, Run the project and
browse the Index action of HomeController. You will get output as shown in
below screenshot.
Final Output :
Thanks for Reading ....
See my other article also :
ASP.NET , C# , Javascript , Bootstrap , AngularJs , Model View Controller , Java , Visual Studio , Ready made projects , MVC 4.0 , .NET Core

