Home > Back-end >  List<model> doesn't contain a definition and no accessible extension method
List<model> doesn't contain a definition and no accessible extension method

Time:01-19

I am getting error on this line:

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

Error details:

List<MyModel> does not contain a definition for FirstName and no accessible extension method FirstName accepting a first argument of type List<MyModel> could be found

I checked my MyModel class and it does haveFirstName property.

There's no error on this line which is weird

@Html.DisplayFor(modelItem => item.FirstName)

Controller class:

    // GET: MyController/DisplayData
    public async Task<IActionResult> DisplayData()
    {
        try
        {
            IQueryable<MyModel> query = await _services.Get_All_Data();
            List<MyModel> myData = await query.AsNoTracking().ToListAsync();

            return View(myData);
        }
        catch
        {
            return View();
        }
    }

View (DisplayData class):

@model List<MyModel>

@{
     ViewData["Title"] = "DisplayData";
 }

<h1>DisplayData</h1>

<table >
    <thead>
         <tr>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
             <th></th>
        </tr>
   </thead>
   <tbody>
   @foreach (var item in Model) {
         <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
           </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
}
    </tbody>
</table>

CodePudding user response:

Because a basket of apples is not an apple. And a list of MyModel is not a MyModel.

To use that property, drill into an item in the list:

@Html.DisplayNameFor(model => model.First().FirstName)

(Unless something has changed, this should work even for an empty list. Though intuitively one would expect an error on .First() for a list with no contents, the framework internally just uses this to in some way reflect to the property name and not actually invoke the query on the list.)

  • Related