blog

Home / DeveloperSection / Blogs / Various ways to pass data from controller to view in asp.net mvc 4

Various ways to pass data from controller to view in asp.net mvc 4

Sumit Kesarwani11420 10-Feb-2014

In this blog, I’m explaining what are the various ways to pass data from controller to view in asp.net mvc 4 application.

ViewData

ViewData is a built-in dictionary object that can be accessed and set with string type key values. It is derived from “ViewDataDictionary” class and is a very handy data structure when it comes to passing data from Controller to View. The data is only alive for one request and cannot persist between request.

The only problem with ViewData is that the type casting is required for complex data types at the location where the data is being extracted.

Example
HomeController.cs file code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PassDataControllerToView.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        publicActionResult Index()
        {
            ViewData["Time"] = DateTime.Now.ToString();
            return View();
        }
    }
}

Index.cshtml file code:
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
       Current Time : @ViewData["Time"]<br/>
    </div>
</body>
</html>

Output

Various ways to pass data from controller to view in asp.net mvc 4


ViewBag

ViewBag data structure written as a wrapper over the ViewData so that the type casting for complex objects will not be required if we use ViewBag. ViewBag comes with all the benefits of ViewData with an additional benefit that type casting is not required

Example
HomeController.cs file code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PassDataControllerToView.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        publicActionResult Index()
        {
            ViewBag.Greeting = "Passing message from controller to view using VIEWBAG";
            return View();
        }
    }
}

Index.cshtml file code:
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Greeting
    </div>
</body>
</html>

Output

Various ways to pass data from controller to view in asp.net mvc 4

Model

The best and recommended way to pass the data from a Controller to View is by using Model classes. If we create a strongly typed view than that view is capable of accessing the object/model that is being passed to it from the controller. So for most cases where we need to use some data we should create strongly typed views and pass on Model objects to the views.

Example
HomeController.cs file code:
using PassDataControllerToView.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PassDataControllerToView.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        publicActionResult Index()
        {
            return View();
        }
        publicActionResult Student()
        {
            Student student = newStudent();
            student.studentID = "1001";
            student.Name = "Mark david";
            student.Address = "New York";
            return View(student);
        }
    }
}

Student.cs file code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PassDataControllerToView.Models
{
    publicclassStudent
    {
        publicstring studentID { get; set; }
        publicstring Name { get; set; }
        publicstring Address { get; set; }
    }
}

Student.cshtml file code:
@model PassDataControllerToView.Models.Student
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>Student</title>
</head>
<body>
    <div>
        Student ID : @Model.studentID<br/>
        Student Name : @Model.Name<br/>
        Student Address : @Model.Address
    </div>
</body>
</html>

Output

Various ways to pass data from controller to view in asp.net mvc 4

ViewModel

ViewData can be used to pass simple and small data from controller to the view. When we want to pass the data to the view from multiples class, then we create a class which contains the objects of all classes and the object of this will pass to the view. This type of class is called the ViewModel.

Example
HomeController.cs file code:
using PassDataControllerToView.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PassDataControllerToView.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        publicActionResult Index()
        {
            return View();
        }
publicActionResult showStudentInfoWithMessage()
        {
            Student student = newStudent();
            student.studentID = "1001";
            student.Name = "Jim Hamilton";
            student.Address = "New Jersey";
            Message msg = newMessage();
            msg.message = "Message is coming from Message Model Class";
            showStudentInfoWithMessage show = newshowStudentInfoWithMessage();
            show.student = student;
            show.message = msg;
            return View(show);
        }

Student.cs file code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PassDataControllerToView.Models
{
    publicclassStudent
    {
        publicstring studentID { get; set; }
        publicstring Name { get; set; }
        publicstring Address { get; set; }
    }
}

Message.cs file code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PassDataControllerToView.Models
{
    publicclassMessage
    {
        publicstring message { get; set; }
    }
}

showStudentInfoWithMessage.cs file code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PassDataControllerToView.Models
{
    publicclassshowStudentInfoWithMessage
    {
        publicStudent student { get; set; }
        publicMessage message { get; set; }
    }
}

showStudentInfoWithMessage.cshtml file code:
@model PassDataControllerToView.Models.showStudentInfoWithMessage
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>showStudentInfoWithMessage</title>
</head>
<body>
    <div>
        Student ID : @Model.student.studentID<br/>
        Student Name : @Model.student.Name<br/>
        Student Address: @Model.student.Address<br/><br/>
        Message : @Model.message.message
    </div>
</body>
</html>

Output

Various ways to pass data from controller to view in asp.net mvc 4

TempData

 When data transfer is done using ViewData or Viewbag, the data is only alive for current request. The data is lost if a redirection takes place i.e. one Action redirects to another action. For the scenarios where we need to persist the data between actions/redirection another dictionary object called TempData can be used. It is derived from TempDataDictionary. It is created on top of session. It will live till the redirected view is fully loaded.

Example
HomeController.cs file code:
using PassDataControllerToView.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PassDataControllerToView.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        publicActionResult Index()
        {
            return View();
        }
publicActionResult bookData()
        {
            Book book = newBook();
            book.BookID = "1001";
            book.BookName = "Science Book";
            TempData["BookData"] = book;
            return RedirectToAction("tempDataExample");
        }
        publicActionResult tempDataExample()
        {
            Book book = TempData["BookData"] asBook;
            return View(book);
        }

Book.cs file code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PassDataControllerToView.Models
{
    publicclassBook
    {
        publicstring BookID { get; set; }
        publicstring BookName { get; set; }
    }
}

tempDataExample.cshtml file code:
@model PassDataControllerToView.Models.Book
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>tempDataExample</title>
</head>
<body>
    <div>
       Book ID : @Model.BookID<br/>
       Book Name :  @Model.BookName
    </div>
</body>
</html>

Output
Various ways to pass data from controller to view in asp.net mvc 4

Sessions

Session is the way to persist the data till the current session is alive. If we need some data to be accessible from multiple controllers, actions and views then Session is the way to store and retrieve the data.

Example
HomeController.cs file code:
using PassDataControllerToView.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PassDataControllerToView.Controllers
{
    publicclassHomeController : Controller
    {
        //
        // GET: /Home/
        publicActionResult Index()
        {
            return View();
        }
publicActionResult bookData2()
        {
            Book book = newBook();
            book.BookID = "1001";
            book.BookName = "Science Book";
            Session["BookData"] = book;
            return RedirectToAction("sessionExample");
        }
        publicActionResult sessionExample()
        {
            Book book = Session["BookData"] asBook;
            return View(book);
        }
    }
}

sessionExample.cshtml file code:
@model PassDataControllerToView.Models.Book
@{
    Layout = null;
}
<!DOCTYPEhtml>
<html>
<head>
    <metaname="viewport"content="width=device-width"/>
    <title>sessionExample</title>
</head>
<body>
    <div>
        Book ID : @Model.BookID<br/>
        Book Name : @Model.BookName
    </div>
</body>
</html>

Output

Various ways to pass data from controller to view in asp.net mvc 4


Updated 18-Sep-2014

Leave Comment

Comments

Liked By