【问题标题】:Pass a List to View In MVC将列表传递给在 MVC 中查看
【发布时间】:2016-02-25 12:14:49
【问题描述】:

我正在将一个列表值传递给我的视图。但是我收到“传递到字典中的模型项的类型为'System.Collections.Generic.List”的错误。这是我的控制器操作:

public ActionResult Index()
    {
        Test t = new Test();
        List<Customer> myList= t.GetData();
        return View(myList);
    }

这里是视图:

@model List<AsyncActions.Models.Test>
@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>
<table border="1" cellpadding="4">
    @foreach (var row in Model)
    {
    <tr>
        @*<td>@row."CustomerID"</td>
        <td>@row."CustomerCode"</td>*@
    </tr>
}

这是我的模型:

namespace AsyncActions.Models
{
public class Test
{
    public List<Customer> GetData()
    {
        try
        {
            Customer c = new Customer();
            List<Customer> cst = new List<Customer>();
            for (int i = 0; i < 10; i++)
            {                    
                c.CustomerID = i;
                c.CustomerCode = "CST"+i;
                cst.Add(c);
            }
            return cst;
        }
        catch (Exception)
        {
            throw new NotImplementedException();
        }

    }
}
public class Customer
{
    public int CustomerID { get; set; }
    public string CustomerCode { get; set; }
}
}

我已经尝试从视图中删除 List。当我这样做时,我收到一个错误,因为“foreach 语句无法对'AsyncActions.Models.Test' 类型的变量进行操作,因为'AsyncActions.Models.Test' 不包含'GetEnumerator”的公共定义。我已经尝试了很多东西。我检查了这个 link ,但这并没有解决我的问题。我无法找出我错过了什么。非常感谢任何帮助。

【问题讨论】:

  • 看起来你还没有发布你的实际代码。 ` List myList= t.GetData();` 表示您的模型是List&lt;Customer&gt;。但是你的视图有别的东西作为模型。
  • @kosala 请查看更新后的问题。
  • 我想你已经有了下面的答案。此评论与您的​​问题无关。您的模型中存在错误。您应该在 for 循环中定义 Customer c = new Customer();
  • @kosala 是的,我已经得到了答案。非常感谢您找出错误。

标签: c# asp.net-mvc asp.net-mvc-3 model-view-controller view


【解决方案1】:

在您的视图中使用它应该可以解决问题:

@model List<Customer>

【讨论】:

  • 你是对的。我按你说的试过了,也有效。谢谢,最后我将模型定义更改为@model IEnumerable。这解决了我的问题。
【解决方案2】:

您应该将模型的定义更改为:

@model List<Customer>
@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>
<table border="1" cellpadding="4">
    @foreach (var row in Model)
    {
    <tr>
        @*<td>@row."CustomerID"</td>
        <td>@row."CustomerCode"</td>*@
    </tr>
}

【讨论】:

  • 你是对的。我按你说的试过了,也有效。谢谢,最后我将模型定义更改为@model IEnumerable。这解决了我的问题。
【解决方案3】:

将您的 @model 更改为 @model IEnumerable&lt;Customer&gt;

@model IEnumerable<Customer>
@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>
<table border="1" cellpadding="4">
    @foreach (var row in Model)
    {
    <tr>
        @*<td>@row."CustomerID"</td>
        <td>@row."CustomerCode"</td>*@
    </tr>
}

【讨论】:

  • 谢谢,我将模型定义更改为@model IEnumerable。这解决了我的问题。
【解决方案4】:

你的视图模型应该是

@model List<Customer>

【讨论】:

  • 你是对的。我按你说的试过了,也有效。谢谢,最后我将模型定义更改为@model IEnumerable。这解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
相关资源
最近更新 更多