Infolink

 

Search This Blog

Nov 29, 2012

How to pass data from controllers to views in ASP.NET MVC ?

The controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for display purpose.

As an ASP.NET developer your choice would be to use session variables, view state or some other ASP.NET session management object.


The problem with using ASP.NET session or view state object is the scope. ASP.NET session objects have session scope and view state has page scope. For MVC we would like to see scope limited to controller and the view. In other words we would like to maintain data when the hit comes to controller and reaches the view and after that the scope of the data should expire.

That’s where the new session management technique has been introduced in ASP.NET framework i.e. ViewData.

Step1:- Create project and set viewdata

So the first step is to create a project and a controller. In the controller set the viewdata variable as shown in the below code snippet and kick of the view.
[HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["CurrentTime"] = DateTime.Now.ToString();

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }

Step 2:- Display view data in the view.

The next thing is to display the data in the view by using the percentage tag. One important point to note is the view does not have a behind code. So to display the view we need to use the <%: tag as shown in the below code snippet to display the data.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: ViewData["CurrentTime"] %></h2>
</asp:Content>

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...