0

Scaffolded Views in MVC5 w/ EF6 produce Code like this for an Overview page:

@*Useroverview.cshtml*@
@model IEnumerable<Models.tblUser>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @*One of the lines in question*@
            @Html.DisplayNameFor(model => model.username) 
        </th>
        <th>
            @*Another line in question*@
            @Html.DisplayNameFor(model => model.email)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        @*looping through the elements and displaying the values*@
    }

</table>

How is it possible that the line I marked works? When I try that with proper ViewModels it does not allow me to do something exactly like it (i.e. access a Class' Member even though I'm accessing it through a List, but not through an element.

@Html.DisplayNameFor(model => model.username)

If my model is

@model IEnumerable<Models.MyOwnModel>

and contains, among other things, an IEnumerable users, I cannot access the property name with:

@Html.DisplayNameFor(model => model.users.username)

but only like so:

@Html.DisplayNameFor(model => model.users.ElementAt(0).username)

Edit: In the end, the result should be a line that writes out the variable's name (or whatever has been set as the display name in the model class).

  • `model => model.users.username` is a lambda expression that is declaring a local variable named `model`. In this case `model` is not an `IEnumerable`, it actually is a single instance. This local variable has nothing to do with any other variables you may have named `model`. – Brandon Kramer Mar 20 '17 at 12:58
  • I realize am able to rename that variable in the lambda expression to whatever I like, but that is exactly my issue: Why does that variable have access to the username in the scaffolded example, but not when I use it in the example with the custom viewmodel? – CognitionGuy Mar 20 '17 at 13:03
  • What type is `@Html`? Is the `@Html` object in your viewmodel the same as the one in the view? – Brandon Kramer Mar 20 '17 at 13:04
  • Also, this may answer your question: http://stackoverflow.com/a/20808067/7604843 – Brandon Kramer Mar 20 '17 at 13:05
  • `@Html` is a Razor helper function which produces html. Maybe I didn't phrase my question clear enough, sorry - English is not my first language. I'm just confused why the scaffolded version has access to a class' properties even though it's in an `IEnumerable` and another time it has not (if the `IEnumerable` is within another class). But I suppose that's because `tblUser` is a class automatically generated by EF so it has access to its definition? – CognitionGuy Mar 20 '17 at 13:11

0 Answers0