Home > Software engineering >  MVC code, throwing error on index.cstml, non-static field error
MVC code, throwing error on index.cstml, non-static field error

Time:11-25

I have this index.cshtml code:

@model IEnumerable<Desa.Models.Person>

<p>Person List Page</p>

<table border="1">
    <tr>
        <th>Name</th>
        <th>Address</th>
        <th>Phone</th>
        <th>Email</th>
    </tr>
     @foreach (var item in Model)
        {
        <tr>
            <td>@Person.name</td>
            <td>@Person.email</td>
            <td>@Person.phone  </td>
            <td>@Person.address</td>
        </tr>
        }
    </table>

And the Person model:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Desa.Models
{
    public class Person
    {
        [Key]
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string address { get; set; }
    }
}

On the Index.cshtml part it's throwing an error saying:

CS0120 An object reference is required for the non-static field, method, or property 'Person.name' Desa
C:\Users\qendr\source\repos\Desa\Desa\Views\Person\Index.cshtml 15
Active

I'm not quite sure what might be the issue, any help?

CodePudding user response:

You are using the foreach to iterate the IEnumerable<Desa.Models.Person> collection. Therefore it is necessary to reference to the collection item like below:

@foreach (var item in Model)
{
<tr>
    <td>@item.name</td>
    <td>@item.email</td>
    <td>@item.phone  </td>
    <td>@item.address</td>
</tr>
}

For details see the Microsoft documentation: Strongly typed views

  • Related