Thursday, 5 March 2015

showing viewdata in MVC 5 on razor view

In MVC Viewdata is the way to maintain the data for passing it  from Controller to View.

Just giving the below example to pass the ViewData in MVC5 on Razor View;

You have defined or pass the Viewdata from controller like below;

public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult MyHomeview()
        {
            ViewData["Datetime"] = DateTime.Now.ToString();
            return View();
        }
       }


Now in View just getting that Viewdata and displaying it to the UI;
For this you need the below code only on your .CHTML code

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>MyHomeview</title>
</head>

<body>
    <div>
        My MVC View  @Html.Label(ViewData["Datetime"].ToString()) 
    </div>
</body>

</html>

And output will be display as below;

No comments:

Post a Comment