【问题标题】:How to display IEnumerable in view? [duplicate]如何在视图中显示 IEnumerable? [复制]
【发布时间】:2019-11-07 02:45:32
【问题描述】:

我正在为产品做评论部分,并且在显示 cmets 视图时遇到了一些问题。我用 2 个模型制作模型以在一个视图中显示它们,但是我将 IEnumerable 显示为列表的方式让我出错。如何修改我的代码以使其正常工作?

型号

public class DetailsViewModel
{
    public Product Product { get; set; }
    public IEnumerable<Comments> Comments { get; set; }
}

控制器

    public ActionResult ProductDetails(int? id)
    {
        DetailsViewModel detailsViewModel = new DetailsViewModel();
        detailsViewModel.Product = db.Product.Find(id);//this is working
        detailsViewModel.Comments = db.Comments.Where(c => c.Id_Product == id).OrderBy(x => x.DateComment).ToList();
        return View(detailsViewModel);
    }

查看

@model Database.Models.DetailsViewModel
<ul>
@Html.DisplayFor(x => x.Comments.DateComment) //getting error here 'IEnumerable<Comments>'
@Html.DisplayFor(x => x.Comments.Comment)     // does not containt definiton for 'Comment'
<ul>

我想得到这样的东西:

  • 2019-06-25:Foo
  • 2019-06-25:FooFoo
  • 【问题讨论】:

    • 你需要一个foreach
    • foreach 语句无法对“DetailsViewModel”类型的变量进行操作,因为“DetailsViewModel”不包含“GetEnumerator”的公共实例定义

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


    【解决方案1】:

    为您的评论模型创建一个DisplayTemplate,然后简单地使用

     @Html.DisplayFor(x => x.Comments)
    

    它将遍历它们并使用 DisplayTemplate 来呈现每个。

    【讨论】:

    • 它给了我一些奇怪的东西 System.Data.Entity.DynamicProxies.Product_1F161BFA07EF87380337F5397E9B83A40B176F245617AD31ACF72F5F0598D1BF 而不是 cmets
    • 您是否为您的 Comment 模型创建了一个 DisplayTemplate,因为答案的第一个词表明您必须这样做?
    【解决方案2】:

    您可以使用foreach 循环来实现您的功能。 foreach 循环将遍历您的IEnumerable 并显示列表中的每个元素。具体到您的情况,您可以这样做:

    <ul>
      @foreach(var comment in Model.Comments)
      {
       <li>@comment.DateComment</li>
       <li>@comment.Comment</li>
      }
    <ul>
    

    【讨论】:

    • 在评论前使用@ &lt;li&gt;comment.DateComment&lt;/li&gt;
    • 抱歉错过了。已进行所需的编辑。谢谢
    • 不应该是Model.DetailsViewModel.CommentsModel.Comments
    • 是的,应该是Model.Commentsty 寻求帮助,它为我解决了问题
    猜你喜欢
    • 1970-01-01
    • 2019-09-07
    • 2015-02-16
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 2012-09-20
    相关资源
    最近更新 更多