Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewData and ViewModel in MVC ASP.NET

I'm new to .Net development, and now are following NerdDinner tutorial. Just wondering if any of you would be able to tell me

What is the differences between ViewData and ViewModel

(all I know is they are used to pass some form of data from controller to view) and perhaps tell me on what situation should I use ViewData instead of ViewModel and vice versa

Thanks in advance!

Sally

like image 384
Amy Lee Avatar asked Mar 03 '11 06:03

Amy Lee


People also ask

What is ViewData in ASP.NET MVC?

In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary. The only limitation of ViewData is, it can transfer data from controller to view.

What is the difference between view and ViewData is asp net?

It's a communication mechanism within the server call. Difference between ViewBag & ViewData: ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.

What is the difference between view and ViewModel in MVC?

VIEW: ( Platform Specific Code – USER INTERFACE ) What the user sees, The Formatted data. VIEWMODEL: ( Reusable Code – LOGIC ) Link between Model and View OR It Retrieves data from Model and exposes it to the View.

What is ViewModel and model in MVC?

ViewModel = Model that is created to serve the view. ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible. ViewModel serves this purpose. View Model is a model class that can hold only those properties that are required for a view.


1 Answers

What is ViewData ?

  • dictionary object that you put data into, which then becomes available to the view.

ViewData Sample

Controller Action method likes :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var featuredProduct = new Product
        {
            Name = "Smart Phone",
            QtyOnHand = 12
        };

        ViewData["FeaturedProduct"] = featuredProduct;
        return View();
    }
}

How to use ViewData on View ?

@{    
    var viewDataProduct = ViewData["FeaturedProduct"] as Product;
 }
<div>
    Today's Featured Product is!
    <h3>@viewDataProduct.Name</h3>
</div>

What is a ViewModel ?

  • Allow you to shape multiple entities from one or more data models or sources into a single object
  • Optimized for consumption and rendering by the view

Its like :

View Model image

How to use ViewModel with MVC 3 ?

Domain Model

public class Product
    {
        public Product() { Id = Guid.NewGuid(); Created = DateTime.Now; }
        public Guid Id { get; set; }
        public string ProductName { get; set; }
    }

ViewModel

public class ProductViewModel
    {
        public Guid VmId { get; set; }

        [Required(ErrorMessage = "required")]
        public string ProductName { get; set; }

    }

Controller Action Method

[HttpGet]
public ActionResult AddProduct()
{
    //for initialize viewmodel
    var productViewModel = new ProductViewModel();

    //assign values for viewmodel
    productViewModel.ProductName = "Smart Phone";

    //send viewmodel into UI (View)
    return View("AddProduct", productViewModel);
}

View - AddProduct.cshtml

@model YourProject.ViewModels.ProductViewModel //set your viewmodel here

Conclusion

  • By using ViewModel can pass strongly-typed data into View
  • But ViewData is Loosely Typed.So Need to cast data on View
  • ViewModel can use for Complex scenarios such as merging more than one domain model
  • But ViewData can be used only for simple scenarios like bring data for the drop down list
  • ViewModel can use for attribute-based validation scenarios which needed for Ui
  • But Cannot use ViewData for such kind of validations
  • As a best practices always try to use strongly typed data with Views.ViewModel is the best candidate for that.
like image 174
Sampath Avatar answered Oct 02 '22 11:10

Sampath