Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get access to a variable in a View which was created in a Controller?

How can I get access to a variable in a View which was created in a Controller?

like image 683
misho Avatar asked Dec 13 '22 15:12

misho


1 Answers

Either put the variable into the Model that you are using for your View

Or use a ViewBag variable - e.g. from http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx

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(); 
}

and

<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>
<% } %>

although hopefully you'll be using Razor :)

like image 175
Stuart Avatar answered Mar 01 '23 23:03

Stuart