Monday, 4 June 2018

How to pass data from Controller to Views

In this blog, we will see how Controller interacts with View in ASP.Net MVC. In another way, we can say - How to pass data from Controller to View?

There are multiple ways to pass data from Controller to Views.
We will see here one by one.

First, we will create a Model class. In my case, I created a class 'Products' as shown below.


    public class Products
    {
        public int ProductId { get; set; }
        [Required ]
        [StringLength(300)]
        public string ProductName { get; set; }
        [Required]
        [ProductCostCheck]
        public int ProductCost { get; set; }
        [Display (Name="Discount Value")]
        public int Discount { get; set; }
    }


Now Create a Controller class called 'ProductController' and add Action - 'DisplayProductName'

Pass data from Controller to View

1. Pass data by Model

In below Action, we passed our Model data to View.

        public ActionResult DisplayProductName()
        {
            var product = new Products { ProductName = "Laptop" };
            return View(product);
        }

Products class has a property called ProductName. Display the ProductName via Model as shown below.

@Model.ProductName

2. Pass data using ViewBag

ViewBag is of Dynamic Type.
In below action, I have used ViewBag with a dynamic property Product i.e. ViewBag.Product and assigned Product Name as shown below.

public ActionResult DisplayProductName()
        {
            var product = new Products { ProductName = "Laptop" };
            ViewBag.Product = product;
            return View();
        }

You can access data with ViewBag in your View as shown below.


@ViewBag.Product.ProductName

3. Pass data using ViewData

Every controller has a property called as 'ViewData' of type ViewDataDictionary.
We can simply assign product name to the ViewData.

public ActionResult DisplayProductName()
        {
            ViewData["ProdName"] = "Laptop"
            return View();
        }

Now you can access data in your View as shown below.
The problem with this approach is when you make changes to Controller, ViewData will not reflect in View.

For eg - In Controller, you changed
ViewData["ProdName"] = "Laptop"; to ViewData["NewProdName"] = "Laptop";
Then in your View, you have to go and change it manually.

@ViewData["ProdName"]


No comments:

Post a Comment

Dear Readers, Please post your valuable feedback in the comment section if you like this blog or if you have any suggestions. I would love to hear the same from you. Thanks