Uses of ViewBag and Model in ASP.NET MVC

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. You can visit the following link for help: How to create first Application by 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”;
}

@ViewBag.Title.




@ViewBag.Message


@Model.Name


Location : @Model.Location

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

@Model.Name


Location : @Model.Location
Now run the project and click About link. You will see the following output.
output

Recommended articles:

1. Introduction to ASP.NET MVC

2.How to create first Application by ASP.NET MVC

Please share, if it is helpfulShare on FacebookShare on LinkedInTweet about this on TwitterShare on Google+Email this to someonePrint this page

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>