Viewdata and viewmodel in mvc asp net


When working with ASP.NET MVC, it is to pass data from the to the view. There are two commonly used approaches for this: ViewData and . In this article, we will explore these two approaches and discuss when to use each one.

Using ViewData

ViewData is a dictionary-like object that allows you to pass data from the controller to the view. It is a dynamic object, which means you can store any type of data in it. However, since it is not strongly typed, you need to cast the data back to its original type in the view.

Here is an example of how to use ViewData in ASP.NET MVC:

// Controller
public  Index()
    ViewData["Message"] = "Hello, World!";
    return View();

// View
    var message = (string)ViewData["Message"];


In this example, we set the of the “Message” key in the ViewData dictionary in the controller. Then, in the view, we retrieve the value using the same key and cast it to a string. Finally, we the message in an HTML heading element.

Using ViewModel

A ViewModel is a custom that is specifically designed to hold data for a view. Unlike ViewData, a ViewModel is strongly typed, which means you can define the properties and their in the class. This provides better type safety and makes the code easier to understand and maintain.

Here is an example of how to use a ViewModel in ASP.NET MVC:

// ViewModel
public class MessageViewModel
    public string Message { get; set; }

// Controller
public ActionResult Index()
    var viewModel = new MessageViewModel
        Message = "Hello, World!"
    return View(viewModel);

// View
@model MessageViewModel


In this example, we define a MessageViewModel class with a single property called “Message”. In the controller, we create an of the ViewModel and set the value of the Message property. Then, we pass the ViewModel to the view using the return View(viewModel) statement. In the view, we declare the model type using the @model directive and access the Message property using the @Model object.


Both ViewData and ViewModel are useful approaches for passing data from the controller to the view in ASP.NET MVC. ViewData is a dynamic object that allows you to store any type of data, but it requires casting in the view. ViewModel, on the other hand, is a strongly typed class that provides better type safety and makes the code easier to understand and maintain. Choose the that best suits your needs and the complexity of your application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents