Uses Of ViewBag And Model In ASP.NET MVC

1 minute read

In my series tutorial on ASP.NET MVC, I will try to develop an application which is called Training Management System (TMS). In this project, I will keep an employee’s skill matrix on the basis of training. Rather than this, I will keep employee information, training information and many more. I will continuously modify the project by implementing different features and functionality of ASP.NET MVC.

In this article, I will show how to implement a simple model and ViewBag. ASP.NET MVC offers us ViewBag for passing data from controller to view. ViewBag is dynamic object. Let’s create a project using asp.net MVC.

Step 1: Create a Model name – AboutModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace TMS.Models
{
  public class AboutModel
  {
    public string Name { get; set; }
    public string Location { get; set; }
  }
}

Step 2: Edit HomeController and update the About action as follows

public ActionResult About()
{
  ViewBag.Message = "Company Information";
  
  var aboutModel = new AboutModel();
  aboutModel.Name = "Leadsoft Bangladesh Limited";
  aboutModel.Location = "41/6, Purana Platan, Sawdesh Tower, Dhaka - 1000";
  
  return View(aboutModel);
}

In this action, you will see, ViewBag.Message is used to hold a string, we will use it in view. I use a AboutModel object name aboutModel with its two property which will also use in the view.

Step 3: Edit About view (About.cshtml) as follows

@model TMS.Models.AboutModel
@{
ViewBag.Title = "About";
}
<hgroupclass="title">
<h1>@ViewBag.Title.</h1>
</hgroup>
<div>
<h2>@ViewBag.Message</h2>
<h2>@Model.Name</h2>
Location : @Model.Location
</div>

Add @model TMS.Models.AboutModelat the top of the view. To view the ViewBag data use like @ViewBag.Message . Use AboutModel value like

<h2>@Model.Name</h2>
Location : @Model.Location

Now run the project and click About link, you will see the output.