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

ViewData is a dictionary, which will contains data to be passed between controller and views. Controller will add items to this dictionary and view reads from it. While retrieving, the data it needs to be Type Casted to its original type as the data is stored as objects and it also requires NULL checks while retrieving. ViewData is used for passing value from Controller to View. ViewData is available only for Current Request. It will be destroyed on redirection.


ViewData Example:-

On View Page:-
Here I have created ViewDataMessage name.

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ViewDataMessage</title>
</head>
<body>
    <div>
        @ViewData["Message"]
    </div>
</body>
</html>

On Controller Page:-


Here I have created ViewData name. Here I have call View that name is ViewDataMessage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCCODESOLUTIONS.Controllers
{

    public class ViewDataController : Controller
    {
        // GET: ViewData
        public ActionResult ViewDataMessage()
        {
            ViewData["Message"] = "ViewData is a dictionary, which will contains data to be passed between controller and views.";
            return View();
        }
    }

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

No comments:

Powered by Blogger.