Setting Data in Controller

So far, we've been defining our data directly in the view. To be honest, doing it this way is unusual.

Actually, it is controller job to supply the data to the view. Moving the data to our controller also follows the separation of concerns design principle.

Cut the code within @ line inside View class. Copy it inside the Detail function in Controller class.

It is called ViewBagto pass the variable from Controller class to View class.

public ActionResult Detail()
{
    ViewBag.SeriesTitle = "The Amazing Spider-Man";
    ViewBag.IssueNumber = 700;
    ViewBag.Description = "<p>Final issue! Witness the final hours of Doctor Octopus' life and his one, last, great act of revenge! Even if Spider-Man survives... <strong>will Peter Parker?</strong></p>";
    ViewBag.Artists = new string[]
    {
        "Script: Dan Slott",
        "Pencils: Humberto Ramos",
        "Inks: Victor Olazaba",
        "Colors: Edgar Delgado",
        "Letters: Chris Eliopoulos"
    };

    return View();
}

And in our View class.

<div>
    <h1>@ViewBag.SeriesTitle</h1>
    <h2>Issue #@ViewBag.IssueNumber</h2>

    <h5>Description:</h5>
    <div>@Html.Raw(ViewBag.Description)</div>

    @if (ViewBag.Artists.Length > 0)
    {
        <h5>Artist:</h5>
        <div>
            <ul>
                @foreach (var artist in ViewBag.Artists)
                {
                    <li>@artist</li>
                }
            </ul>
        </div>
    }
</div>

results matching ""

    No results matching ""