-->

Tuesday, October 8, 2013

How to pass data from Controller to View in MVC

How to pass data from Controller to View in MVC

Introduction 

In my previous post we have been learned How to create a new controller in MVC
Bydefault a controller class contains a Index method and that method returns a ActionResult type value. So we can return View in Index method. Here we will use ViewBag object for initializing dynamic properties such as

public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            ViewBag.name = "jacob";
            return View();
        }


    }
If we want to pass Data ("jacob") from Controller class to View then first we would create a View.

How to create a View in View folder

Step-1 : Create a Directory which name same as Controller class ( here we use Home)
Step-2: Right Click on Home Directory and add new View which name same as Action Controller method (here we use Index.cshtml)
Step-3: Open Index.cshtml page and access Dynamic properties of View Bag object using "@" symbol such as
<h2>@ViewBag.name</h2>

Note :Must Check your Directory structure
Directory structure of MVC file






Output


How to pass data from Controller to View in MVC

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved