【问题标题】:MVC code, throwing error on index.cstml, non-static field errorMVC 代码,在 index.cstml 上抛出错误,非静态字段错误
【发布时间】:2022-01-03 06:27:43
【问题描述】:

我有这个index.cshtml 代码:

@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>

还有Person 模型:

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; }
    }
}

Index.cshtml 部分,它抛出一个错误:

CS0120 非静态字段、方法或属性需要对象引用 'Person.name' Desa
C:\Users\qendr\source\repos\Desa\Desa\Views\Person\Index.cshtml 15
活跃

我不太确定可能是什么问题,有什么帮助吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc razor


    【解决方案1】:

    您正在使用foreach 迭代IEnumerable&lt;Desa.Models.Person&gt; 集合。因此有必要参考如下集合项:

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

    有关详细信息,请参阅 Microsoft 文档:Strongly typed views

    【讨论】:

    • 哦,我的错!成功了,感谢您的检查!
    猜你喜欢
    • 2023-03-03
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多