Access a variable in a View created in a Controller

A spot specifically for MVC (and version). Tips and tricks.
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces.
Post Reply
dzcadii
Posts: 94
Joined: Sun Mar 01, 2015 4:36 am

Access a variable in a View created in a Controller

Post by dzcadii » Sun Mar 01, 2015 6:42 pm

:idea: Access a variable in a View created in a Controller:

In your controller:

Code: Select all

public ActionResult Index()
{
    List<string> colors = new List<string>();
    colors.Add("red");
    colors.Add("green");
    colors.Add("blue");

    ViewBag.ListColors = colors; //colors is List
    ViewBag.DateNow = DateTime.Now;
    ViewBag.Name = "Hajan";
    ViewBag.Age = 25;
    return View(); 
}
In your view:

Code: Select all

<p>
    My name is 
    <b><%: ViewBag.Name %></b>, 
    <b><%: ViewBag.Age %></b> years old.
    <br />    
    I like the following colors:
</p>
<ul id="colors">

<% foreach (var color in ViewBag.ListColors) { %>
    <li>
        <font color="<%: color %>"><%: color %></font>
    </li>
<% } %>
Reference:
http://stackoverflow.com/questions/5181 ... controller

Post Reply