If you develop web applications in ASP.NET MVC, you should definitely learn how to pass your “Model” data to the “View” using the “Controllers”. This post will show you 4 different ways to accomplish that. Start by opening Visual Studio 2012 and creating an ASP.NET MVC web application. You can do that, selecting :
File -> New Project -> ASP.NET MVC 4 Web Application
Click OK and then, choose the Basic template and Razor as the view engine as follows.
Click OK and finish the “Create Project..” Wizard. Create a Model class named “Product” in the Models folder of your solution. This class will be used as a Model class for passing data to Views. Right click the Models folder and choose Add.. -> Class. Name the new class “Product” and make sure you make it public. Then add a few properties such as Id, Name or Description.
namespace MvcPassDataToView.Models { public class Product { public long Id { get; set; } public string Name { get; set; } public string Description { get; set; } public decimal price { get; set; } } }
Right click the Controllers folder and select “Add -> Controller”. Name the controller “ProductsController” and choose “Empty MVC Controller” for template. Click OK.
Before running the application for the first time, you need to tell MVC Framework which is the default controller and action that will be used when the application is deployed. Open the “RouteConfig.cs” file that relies under the App.Start folder and change the default Controller from “Home” to “Products”.
public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Products", action = "Index", id = UrlParameter.Optional } ); } }
This is not an MVC Routing tutorial but all you need to know for now, is that when you run your application the Index action of your ProductsController controller will be invoked. Build and run your solution. You will get the following error:
This error occurs because despite the fact that the Index action of your ProductsController class was invoked, yet there isn’t an Index View. To create that View, simply right click inside the Index action and select “Add view..”. Leave the default values and press Add. A View named “Index” was added in a folder “Products” under the “Views” folder of your solution. Build and run your solution. Now you should see the default contents of you Index View.
It is time to test the different ways we can use to pass data from controller to the View. In the Index action of your controller create a Product object and assign it to a ViewData dictionary object as follows.
public ActionResult Index() { Product cap = new Product { Id = 1, Name = "Golf cap", Description = "A nice cap to play golf", price = 10m }; ViewData["MyProduct"] = cap; return View(); }
Make sure you have added a using statement for your Product Model class.
Change the Index View file contents as follows, build and run your application.
@using MvcPassDataToView.Models @{ ViewBag.Title = "Index"; } <h2>Index</h2> @{ var prod = (Product)ViewData["MyProduct"]; } <h1>Product</h1> <h3>ID: @prod.Id</h3> <h3>Name: @prod.Name </h3> <h3>Description: @prod.Description</h3> <h3>Price: @prod.price</h3>
In the Index View we added a using statement inside a Razor block (@ symbol) because we needed to cast the ViewData[“MyProduct”] object to a Product Model class object. The ViewData dictionary is one way to pass data from controller to View. Though you noticed that you need to cast this object to the Model class in order to use the respective properties. You can solve this, by using another object shared between Controllers and Views, the ViewBag. Simply change the statement
var prod = (Product)ViewData["MyProduct"];
to
var prod = ViewBag.MyProduct;
Your application will run in the same way without needed to cast the shared object.
The third and more appropriate way to pass data from Controller to View, is to pass the Model class object to the View. To demonstrate how this works, change the Index action contents as follows:
public ActionResult Index() { Product cap = new Product { Id = 1, Name = "Golf cap", Description = "A nice cap to play golf", price = 10m }; return View(cap); }
To use that “cap” Product object, you need to tell the Index View that the Binding object is of class “Product”. In the Index View file add the following code at the top of the page.
@model MvcPassDataToView.Models.Product
Now you can access the cap object’s properties using Razor syntax such as:
@Model."property_name"
The Index View’s contents should look like this.
@using MvcPassDataToView.Models @model MvcPassDataToView.Models.Product @{ ViewBag.Title = "Index"; } <h2>Index</h2> <h1>Product</h1> <h3>ID: @Model.Id</h3> <h3>Name: @Model.Name </h3> <h3>Description: @Model.Description</h3> <h3>Price: @Model.price</h3>
The last way to pass data is the TempData object. This object is used to pass data from one request to the next and only. For example, when you successfully add a new product you want to display a message “A new product was added!”. To demonstrate this, add a new action named “TestTempData” in your ProductsController.
public ActionResult TestTempData() { TempData["data"] = "This wont be displayed in the next request! Test it by refreshing the page!"; return RedirectToAction("Index"); }
The above code, assigns a string to the TempData[“data”] object and then invokes the Index action of the same controller. This will result the Index View to be displayed again. Before running the application, add the following line at the end of the Index View.
<h2>@TempData["data"]</h2>
Build the solution and navigate to
http://localhost:"your_port"/Products/TestTempData
You should see the message we added in the TestTempData action.
Try to refresh the page. You will get a System.NullReferenceException. On purpose, I didn’t check if the TempData[“data”] object is null in the Index page (something you should always do) just to show you that this kind of data is accessible only between two requests!
These are the most usual ways to pass data from a Controller to a View in ASP.NET MVC. If you aren’t familiar with the MVC Routing or the Razor syntax, that’s ok, we ‘ll take a look at those in other posts. You can download the project we built from here.
Categories: ASP.NET
Well done sir, great article…
Thanks
Awesome clarity
I followed ur example but I got an error of null reference in the view
please help
Hi Rania, you were right. Simply remove the .ToString() from the
@TempData[“data”].ToString()
In order to see it in action you must first navigate to /products/testtempdata and then refresh the page. I have attached the project at the end of this post.
Kind regards,
C.S
Excellent blog here! Also your web site loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my website loaded up as quickly as yours lol ckackbfgbkkg
Hi Johna, my blog is hosted in wordpress.com.
Kind regards,
C.S
Hello! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts. ckdbceedkecf
Hi Johne, you can find me on @chsakellsBlog. There is a Twitter link to follow in the right panel of this blog too.
Concise, to the point and crystal clear. Nice one dude.
Thanks..that s nic..
I loved the article. It was hard to get such clarity from many other website. Thanks so much for making it so easy to understand.
excellent article, very practical and clear.
Can you explain similarly for passing user entered data from View to Controller and then to database?
It works nicely. But I only see TWO ways here, instead of ‘4 ways’. Am I missing something ?
but how to do it when we are passing things to controller using json and want to access them in view?
This paper although covering the basics, certainly helped me in a pinch, Thank you
You have touched a life in far away Africa with this wonderful piece. Thank you!
i dont know what the viewbag is doing. plz calrify my doubts?
Kwebblekop!