【问题标题】:Causing problems with foreach into my mvc在我的 mvc 中导致 foreach 出现问题
【发布时间】:2015-07-20 08:20:42
【问题描述】:

这就是我之前发帖的方式,你可以在这里看到。

must retrieve the list from the database

我已经尝试制作我之前描述过的 foreach。但它会导致问题,因为在犯错误时没有运行我的 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);
    }

并且 index.cshtml 的顶部有 i:

@model MentorOrdblind_MVC.Models.Undervisning.Undervisning

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

}

【问题讨论】:

  • @model ....Undervisning 建议单个对象,而不是集合,因此您无法对其进行迭代。你得到什么错误?
  • 请澄清问题。尝试描述问题,有没有错误描述或异常?
  • @StephenMuecke OP 可以迭代它,如果 Undervisning 实现 IEnumerable
  • 请解释一下你的意思 “它会导致问题,因为我的 foreach 在出错时没有运行”。您预计会发生什么,实际会发生什么以及您尝试过什么使这两者匹配?
  • @CodeCaster :我记录了它是哪种数据类型并添加了编辑。

标签: c# asp.net-mvc asp.net-mvc-4 foreach


【解决方案1】:

您将视图传递给List&lt;T&gt;,但您的模型不是IEnumerable 的类型。因此,您的视图只需要 Undervisning 类型的单个对象,而不是集合。

使用这个:

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

【讨论】:

  • @Grundy 我没有关注。视图只需要一个对象而不是集合。如果Undervisning 中的属性是集合,那么我们应该看到模型来帮助回答。调用 Packages.ToList() 并直接将其分配给模型,意味着它是一个集合而不是单个对象。
  • 如果类Undervisning实现IEnumerable,那么一个对象是相等的集合,可以用foreach迭代
  • @Grundy 这行代码var model = db.Packages.ToList(); 直接暗示模型现在是List&lt;T&gt; 所以如果UndervisningIEnumerable 的类型,那么他现在有一个List&lt;IEnumerable&lt;T&gt;&gt;。这意味着他的 View 仍然需要有 IEnumerable 声明。
  • 现在给我一个错误:传递到字典中的模型项的类型为'System.Collections.Generic.List`1
  • @JesperPetersen 可以使用 @model List&lt;MentorOrdblind_MVC.Models.Undervisning.Undervisning&gt; 但这不重要。内部消息的完整错误是什么?
【解决方案2】:

将您的模型声明更改为:

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

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

【讨论】:

  • 但可能 Undervisning 类实现 IEnumerable :-)
  • 这一行 var model = db.Packages.ToList();直接说model就是list
  • 现在给我一个错误:传递到字典中的模型项的类型为'System.Collections.Generic.List`1
  • 这个错误清楚地说明了问题所在。您尚未共享有关您的类型结构的信息,因此我们不会猜测问题所在。
  • 我记录了它是什么数据类型并添加编辑。
【解决方案3】:

始终牢记从控制器操作传递到视图的内容。如果您仅从操作传递模型,则在操作的相应视图中使用模型引用。如果您通过 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。

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2015-09-07
    • 2012-11-01
    • 2011-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多