Sunday 3 September 2017

ViewBag In MVC Application

In This Article, I would like to know you about the Use Of ViewBag In MVC Application.

Actually ViewBag is a dynamic property, which is used to pass data from Controller To Corresponding View.  And It Is The Wrapper Of ViewData i.e., ViewBag uses ViewData Internally  And ViewData Is Derived From Dictonary Class Called ViewDataDictionary. The Life Of ViewData Is Only Lies In Current Request,But If Redirection Occurs, Then It’s value becomes null. And It Does Not Require Typecasting. So It Is Slower Than ViewData.

Now, We have To add New Model Class Named “Items” In The Model Folder And Add The Below Code:

Items.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC__Simple_MVC_Application.Models
{
    public class Items
    {
        public string ItemId { get; set; }
        public string ItemName { get; set; }
        public string ItemDescription { get; set; }
    }
}

 Now , To Pass The Data From Controller To View, new Contoller Named” ItemsController” Is Added In Controller Folder, And Add  The Below Code As Shown:

ItemsController.cs
using MVC__Simple_MVC_Application.Models;                    
using System.Collections.Generic;
using System.Web.Mvc;

namespace MVC__Simple_MVC_Application.Controllers
{
    public class ItemsController : Controller
    {
        // GET: Items
        public ActionResult Index()
        {
            List<Items> items = new List<Models.Items>()
            {
               new Items() {
               ItemId ="1",
               ItemName ="KeyBoard",
               ItemDescription ="Generic 108 Keys PC And Laptop Black"
           },
           new Items() {
               ItemId ="2",
               ItemName ="Mouse",
               ItemDescription ="Generic Wireless USB  Optical Mouse for Laptop And PC"
           },
           new Items() {
               ItemId ="3",
               ItemName ="Pendrive",
               ItemDescription ="16GB USB 2.0 Pen Drive"
           },
            new Items() {
               ItemId ="4",
               ItemName ="DVD Drive",
               ItemDescription ="USB 2.0 External DVD Drive"
           }
            };
            ViewBag.Items = items;
            return View();
        }
    }
}

Now Add The View By RightClick On The Index Action Method, It Adds Index.cshtml File In the View Folder. Now Add The Below Code  For View:

@{
    ViewBag.Title = "Index";
}
<style>
    table, th, td {
        border: 1px solid black;
    }
</style>
<h2>Item Details</h2>

<table>
    <tr>
        <th>Item Id</th>
        <th>Item Name</th>
        <th>Item Description</th>
    </tr>
    @foreach (var item in ViewBag.items)
    {
        <tr>
            <td>@item.ItemId</td>
            <td>@item.ItemName</td>
            <td>@item.ItemDescription</td>
        </tr>
    }
</table>


Output:


No comments:

Post a Comment

Note: only a member of this blog may post a comment.