misho
misho

Reputation: 1195

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?

Upvotes: 5

Views: 17866

Answers (3)

Stuart
Stuart

Reputation: 66882

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 :)

Upvotes: 10

Intelekshual
Intelekshual

Reputation: 7566

You can add it to the ViewData[] dictionary or the (newer) ViewBag dynamic.

In your controller:

ViewData['YourVariable'] = yourVariable;
// or
ViewBag.YourVariable = yourVariable;

In your view:

<%: ViewData["yourVariable"] %>
// or
<%: ViewBag.YourVariable %>

Upvotes: 1

SLaks
SLaks

Reputation: 887305

You need to send the variable to the view in the ViewModel (the parameter to the View() method) or the TempData dictionary.

Upvotes: 3

Related Questions