ViewBag Tutorial with example in MVC (Model-View- Controller)

ViewBag can be useful when you want to transfer temporary data (which is not included in model) from the controller to the view. The ViewBag is a dynamic type property of ControllerBase class which is the base class of all the controllers.


ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be null if redirection occurs.

ViewBag Example:-

On View Page:-
Here I have created ViewBagMessage name.
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ViewBagMessage</title>
</head>
<body>
    <div>
       @ViewBag.Message
    </div>
</body>
</html>

On Controller Page:-

Here I have created ViewBag name. Here I have call View that name is ViewBagMessage
using System;
using System.Collections.Generic;

using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCODESOLUTIONS.Controllers
{
    public class ViewBagController : Controller
    {
        // GET: ViewBag
        public ActionResult ViewBagMessage()
        {
               ViewBag.Message = "ViewBag only transfers data from controller to view, not visa-versa. ViewBag values will be null if redirection occurs.";
            return View();        }
    }

}



ViewBag Tutorial with example in MVC (Model-View- Controller) ViewBag Tutorial with example in MVC (Model-View- Controller) Reviewed by NEERAJ SRIVASTAVA on 11:58:00 PM Rating: 5

No comments:

Powered by Blogger.