What is ViewBag in Asp.Net MVC C#

asp.net mvc viewbag


in this Asp.netMVCc tutorials explain View bag is used to shares the small amount of data from the controller to view. the View bag is a Dynamic type which means no need to typecasting and downcasting. the lifespan of the View bag is the last current HTTP request.

Example :



namespace Alltechgeeks.Controllers
    {
        public class TestController : Controller
        {
            IList<Test> testList = new List<Test>()
                                {
                                new Test(){id=1, name="Murali"},
                                new Test(){id=2, name="Sathwiq"},
                                new Test(){id=3, name="Siri"},
                                 new Test(){id=4, name="Krishna"}
                                 };
            public ActionResult Index()
            {
                Viewbag.totaltest = testList.Count();
                return View();
            }
        }

}


Go to Index.cshtml page consume the viewbag.totaltest in view

<html>
<h1>
    Total Test : @Viewbag.totaltest
</h1>

</html>

we can assign any number of values and properties to Viewbag.



No comments: