How to pass data from Controller to View in MVC

October 08, 2013 0 Comments

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

Jacob Lefore

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google

0 comments: