导致问题与foreach到我的mvc

本文关键字:我的 mvc foreach 问题 | 更新日期: 2023-09-27 18:03:44

你可以在这里看到我是如何制作上一篇文章的

必须从数据库

检索列表

我已尽力使我的每一个我已经描述过。但是当我在上面出错的时候,它会导致我没有把我的foreach贯穿进去的问题。

Index.cshtml

@foreach (var u in Model)
 {
    <div class="col-md-6 col-sm-6">
       <div class="plan">
          <h3>@u.Name<span>$@u.Price</span></h3>
          <p>@u.Text</p>
       </div>
    </div>
 }

undervisningController.cs

// GET: Undervisning
    public ActionResult Index()
    {
        DatabaseClasseDataContext db = new DatabaseClasseDataContext();
        var model = db.Packages.ToList();
        return View(model);
    }

和top on index。CSHTML有i:

@model MentorOrdblind_MVC.Models.Undervisning.Undervisning
<<p>模型strong> Undervisning.cs
public class Undervisning
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int Hours { get; set; }
    public string Text { get; set; }
}

导致问题与foreach到我的mvc

您正在传递您的视图List<T>,但您的模型不是IEnumerable类型。所以你的视图只期望一个类型为Undervisning的对象,而不是一个集合。

使用:

@model IEnumerable<MentorOrdblind_MVC.Models.Undervisning.Undervisning>

将模型声明更改为:

@model IEnumerable<MentorOrdblind_MVC.Models.Undervisning.Undervisning>

此时你的模型是一个单一的类,而不是一个对象列表

始终记住从控制器动作传递给视图的内容。如果您只从操作传递模型,那么在操作的各自视图中使用模型引用。如果传递List,则在视图中使用IEnumerable模型引用。

If you pass list from action then in the view use:
@model IEnumerable<your model> in the top as reference
If you pass model without a list then use:
@model your model 

在你的情况下,你正在传递列表,所以使用你想要的模型类的IEnumerable。

谢谢