Passing Data From A Controller To A View In ASP.Net MVC
In an ASP.NET MVC application, a controller typically performs the business logic of the application and needs to return the result to the user through a view.
You can use the following objects to pass data between controller and view:
- ViewData
- ViewBag
- TempData
What Is ViewBag ?
- ViewBag is also used to transfer data from a controller to a view.
- ViewBag exists only for the current request and becomes null if the request is redirected.
- ViewBag is a dynamic property based on the dynamic features introduced in C# 4.0.
- ViewBag does not require typecasting when you use complex data type.
The general syntax of ViewBag is as follows:
ViewBag.<PropertyName> = <Value>;
where,
- Property: Is a String value that represents a property of ViewBag.
- Value: Is the value of the property of ViewBag, Value may be a String, object, list, array or a different type, such as int, char, float, double DateTime etc.
Note: ViewBag does not provide compile time error checking. For Example- if you mis-spell keys you wouldn’t get any compile time errors. You get to know about the error only at runtime.
Note: ViewData and ViewBag can access each other data interchangeably.
Source Code Of HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewBagDemo.Models;
namespace ViewBagDemo.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
ViewBag.Message = "Message from View Bag !!";
ViewBag.CurrentDate = DateTime.Now.ToLongDateString();
string[] fruits = { "Apple", "Banana", "Grapes", "Orange" };
ViewBag.FruitsArray = fruits;
ViewBag.SportsList = new List<string>()
{
"Cricket",
"Football",
"Hockey",
"Baseball"
};
Employee Anas = new Employee();
Anas.EmpId = 22;
Anas.EmpName = "Anas Qureshi";
Anas.EmpDesignation = "Manager";
ViewBag.Employee = Anas;
ViewData["CommonMessage"] = "This message is accessible by both ViewBag and ViewData";
int[] MyArray = {10,20,30,40 };
ViewBag.Nums = MyArray;
return View();
}
}
}
Source Code Of Index.cshtml (View)
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<h2>@ViewBag.Message</h2>
<h2>@ViewBag.CurrentDate</h2>
<ul>
@{
foreach (string i in ViewBag.FruitsArray)
{
<li>@i</li>
}
}
</ul>
<ul>
@{
foreach (int i in ViewBag.Nums)
{
<li>@i</li>
}
}
</ul>
<ul>
@{
foreach (string i in ViewBag.SportsList)
{
<li>@i</li>
}
}
</ul>
@{
var a = ViewBag.Employee;
}
<p>@a.EmpId</p>
<p>@a.EmpName</p>
<p>@a.EmpDesignation</p>
<h2>Data comes from ViewData = @ViewData["CommonMessage"]</h2>
<h2>Data comes from ViewBag = @ViewBag.CommonMessage</h2>
Click Below Link to Download Notes Of This Blog
https://www.mediafire.com/file/ww4foc928v1unat/VIEW+BAG+IN+MVC.docx/file
Click Below Link to Download Source Code Project Of This Blog
https://www.mediafire.com/file/ks7e0kqzlac7uyx/ViewBagDemo.rar/file
No responses yet