4 Basic ways to pass data from Controller to View in ASP.NET MVC

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

mvcpassdata1

Click OK and then, choose the Basic template and Razor as the view engine as follows.

mvcpassdata2

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.

mvcpassdata3

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:

mvcpassdata4

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>

mvcpassdata5

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.

mvcpassdata6
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.

Advertisements


Categories: ASP.NET

Tags:

17 replies

  1. Well done sir, great article…

    Thanks

  2. Awesome clarity

  3. 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

  4. 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

  5. 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

  6. Concise, to the point and crystal clear. Nice one dude.

  7. Thanks..that s nic..

  8. 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.

  9. excellent article, very practical and clear.

  10. Can you explain similarly for passing user entered data from View to Controller and then to database?

  11. It works nicely. But I only see TWO ways here, instead of ‘4 ways’. Am I missing something ?

  12. but how to do it when we are passing things to controller using json and want to access them in view?

Trackbacks

  1. URL Routing in ASP.NET MVC – Part 1 | chsakell's Blog
  2. Comment on 4 Basic ways to pass data from Controller to View in ASP.NET MVC by Christos S.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Chara Plessa

The purpose of this blog is to broaden my education, promote experimentation and enhance my professional development. Albert Einstein once said that “If you can’t explain it simply, you don’t understand it well enough” and I strongly believe him!

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Kumikoro

A Front End Developer's Blog

Muhammad Hassan

Full Stack Developer | ASP.NET | MVC | WebAPI | Advanced Javascript | AngularJS | Angular2 | C# | ES6 | SQL | TypeScript | HTML5 | NodeJS, MS candidate @LUMS, Grad & EX-Adjunct Faculty @NUCES-FAST, seasonal blogger & open-source contributor. Seattle, WA.

Software Engineering

Web development

IEvangelist

.NET, ASP.NET, C#, MVC, TypeScript, AngularJS

leastprivilege.com

Dominick Baier on Identity & Access Control

Happy DotNetting

In Love with Technology

Knoldus

Knols of experience to your advantage

knowshnet

Search - Read - Request - Share

Rahul's space

Learn, Share and Grow with me !

Dhananjay Kumar

Developer Evangelist @Infragistics | MVP @Microsoft |

SQL Authority with Pinal Dave

SQL Server Performance Tuning Expert

Conficient Blog

Random bits of tech from @conficient

Code! Code! Code!

SOLID & KISS

Code Wala

Designing and coding

Microsoft Mentalist

A way to start with Microsoft Technologies

Tony Sneed's Blog

A glimpse into the lives of Tony & Zuzana Sneed

Sriramjithendra Nidumolu

Personal Notes of Sriramjithendra

%d bloggers like this: