shan.dye2
shan.dye2

Reputation: 61

How to access values from controller?

Maybe I'm stupid asking this question but I need your help. I'm having problem access the second parameter of the return View. I have this code below:

Model

public struct Hello
{
    public string Hi { get; set; }
}

Controller

public ActionResult Index()
{
    List<Hello> list = new List<Hello>();
    list.Add(new Hello() { Hi = "Test" });
    list.Add(new Hello() { Hi = "Test to display" });
    return View("Index", list);
}

How can I access the list variable in Index page? I want to enumerate the data.

I have this code in my Index.cshtml page:

<h2>Index</h2>
<ul>
    @foreach (var x in list)
    {
        <li>@x</li>
    }
</ul>

Upvotes: 0

Views: 46

Answers (1)

Yogi
Yogi

Reputation: 9769

Make sure that your View is bind with list of type Hello.

@model List<MyNamespace.Hello>

then you can use it in your view like -

<h2>Index</h2>
<ul>
    @foreach (var x in Model)
    {
        <li>@x.Hi</li>
    }
</ul>

Upvotes: 1

Related Questions