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


ASP.NET MVC ASP.NET MVC 
Ratings:
2 Comment(s)
 5288  View(s)
Rate this:

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

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

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        public ActionResult Index()

        {

            ViewData["Time"] = DateTime.Now.ToString();

            return View();

        }

    }

}

Index.cshtml file code:

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div>

       Current Time : @ViewData["Time"]<br />

    </div>

</body>

</html>

Output


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

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        public ActionResult Index()

        {

            ViewBag.Greeting = "Passing message from controller to view using VIEWBAG";

            return View();

        }

    }

}

Index.cshtml file code:

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div>

        @ViewBag.Greeting

    </div>

</body>

</html>

Output

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

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        public ActionResult Index()

        {

            return View();

        }

        public ActionResult Student()

        {

            Student student = new Student();

            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

{

    public class Student

    {

        public string studentID { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }

    }

}

Student.cshtml file code:

@model PassDataControllerToView.Models.Student

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="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

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

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        public ActionResult Index()

        {

            return View();

        }

public ActionResult showStudentInfoWithMessage()

        {

            Student student = new Student();

            student.studentID = "1001";

            student.Name = "Jim Hamilton";

            student.Address = "New Jersey";

            Message msg = new Message();

            msg.message = "Message is coming from Message Model Class";

            showStudentInfoWithMessage show = new showStudentInfoWithMessage();

            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

{

    public class Student

    {

        public string studentID { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }

    }

}

Message.cs file code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace PassDataControllerToView.Models

{

    public class Message

    {

        public string message { get; set; }

    }

}

showStudentInfoWithMessage.cs file code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace PassDataControllerToView.Models

{

    public class showStudentInfoWithMessage

    {

        public Student student { get; set; }

        public Message message { get; set; }

    }

}

showStudentInfoWithMessage.cshtml file code:

@model PassDataControllerToView.Models.showStudentInfoWithMessage

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="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

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

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        public ActionResult Index()

        {

            return View();

        }

public ActionResult bookData()

        {

            Book book = new Book();

            book.BookID = "1001";

            book.BookName = "Science Book";

            TempData["BookData"] = book;

            return RedirectToAction("tempDataExample");

        }

        public ActionResult tempDataExample()

        {

            Book book = TempData["BookData"] as Book;

            return View(book);

        }

Book.cs file code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace PassDataControllerToView.Models

{

    public class Book

    {

        public string BookID { get; set; }

        public string BookName { get; set; }

    }

}

tempDataExample.cshtml file code:

@model PassDataControllerToView.Models.Book

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>tempDataExample</title>

</head>

<body>

    <div>

       Book ID : @Model.BookID<br />

       Book Name :  @Model.BookName

    </div>

</body>

</html>

Output

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

{

    public class HomeController : Controller

    {

        //

        // GET: /Home/

        public ActionResult Index()

        {

            return View();

        }

public ActionResult bookData2()

        {

            Book book = new Book();

            book.BookID = "1001";

            book.BookName = "Science Book";

            Session["BookData"] = book;

            return RedirectToAction("sessionExample");

        }

        public ActionResult sessionExample()

        {

            Book book = Session["BookData"] as Book;

            return View(book);

        }

    }

}

sessionExample.cshtml file code:

@model PassDataControllerToView.Models.Book

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>sessionExample</title>

</head>

<body>

    <div>

        Book ID : @Model.BookID<br />

        Book Name : @Model.BookName

    </div>

</body>

</html>

Output


hiiiii

By kavytha Gandhi on   2 years ago
soooooooooooo Good.

thanks

By Sumit Kesarwani on   2 years ago
Hello Kavytha, 
thanks for your valuable comment.

Don't want to miss updates? Please click the below button!

Follow MindStick