【问题标题】:how do I Separating a List<Object> in razor View如何在 razor 视图中分离 List<Object>
【发布时间】:2020-04-08 17:08:47
【问题描述】:

我从控制器 Example1 和 Example2 向我的视图传递了一个具有两种不同类型的列表。我正在遍历列表以显示其内容。我可以在 Object List 中看到两个列表,[0]-5 Entries 和 [1]-4 Entries。第一个条目是我的 Example1Deutil,第二个是我的 Example2Detail。

我想要做的是通过检查类型在一个表上构建 Example1,在另一个表上构建 Example2。我知道它们属于 Object 类型,因此试图弄清楚如何获得它们的原始类型。所以类型检查工作正常。

编辑:我传入的是Example1Deutil 和Example2Detail 类型的两个List 之一。它们都在传入的List(object)中。

@foreach (var item in Model)
{
    //Edit: This is how I got my List<Object> that contained my two
    // List of List<Example1> and List<Example2> to work.

   foreach(var result in item  as IEnumerable<object>
     //  This was the problem  ^^^^^^^^^^^^^^^^^^^^^
     // The list in the list where just type object and not a List of Objects.
     // and now everything is working. Thank you to those who helped.

    if (result is Models.Example1Models.Example1Detail)
    {
        <table>
             //Example1 contents are different than Example2's contents.
        </table>
    }


    if (result is Models.Example2Models.Example1Detail)
    {
        <table>
             //Example2 Contents
        </table>
    }

【问题讨论】:

  • 那段代码不工作吗?
  • 不,当我使用匹配的模式运行时,它仍然会跳过 if 语句
  • 这意味着对象的类型与您在 if 条件下使用的不同。请检查结果类型并使用模式匹配来绘制表格
  • 想通了。发生的事情是我的模型是 List 与 2 列表一个 Example1 和 Example2 必须使用两个 foreach 循环。第一个 foreach 是 foreach 列表,并将列表与我正在寻找的模型进行比较。第二个 foreach 进入了实际列表。

标签: c# entity-framework razor


【解决方案1】:

控制器

    public ActionResult Contact()
    {
        IList<object> list = new List<object>();
        list.Add(1);
        list.Add("one");

        return View(list);
    }

查看

@model System.Collections.Generic.IEnumerable<object>

@foreach (var result in Model)
{

    if (result is int)
    {
        <div>int</div>
    }

    if (result is string)
    {
        <div>string</div>
    }

}

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2011-03-23
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多