【问题标题】:Cannot apply indexing with [] to an expression of type无法将带有 [] 的索引应用于类型的表达式
【发布时间】:2013-03-24 03:43:40
【问题描述】:

我有这个简单的 MVC 4 代码。我查询数据库并获取所有结果,然后将其保存在 ViewBag 对象中,然后使用 foreach 循环遍历它们,但出现错误:

无法将 [] 索引应用于类型表达式

不让我给他们看。我缺少什么?

这里是实体框架的sql查询

public ActionResult Index()
{
    var ReturnLabelsAndInputsForIndexations = Conexion.MainConexion;

    var IndexationForm = ReturnLabelsAndInputsForIndexations.Labels.ToList();
    ViewBag.IndexationForm = IndexationForm;

    return View();
}

还有索引视图

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <table>
        @foreach (var Indexacion_Labels in ViewBag.IndexationForm)
        { 
            <tr>
                <td>@Indexacion_Labels["LABELS"]//Exception HERE</td>
                <td>@GetInputType(Indexacion_Labels["INPUT_TYPE"], Indexacion_Labels["NAME"])</td>
            </tr>
        }
        </table>
    </div>
</body>
</html

【问题讨论】:

标签: c# asp.net-mvc foreach


【解决方案1】:

ReturnLabelsAndInputsForIndexations.Labels 的类型(无论是什么类型)都没有实现indexer。要解决此问题,您需要将其添加到标签的视图模型中

public this[string index]
{
    get
    {
        ...
    }
}

将您的视图代码更改为类似这样(假设视图模型的属性存在)

<tr>
    <td>@Indexacion_Labels.Labels</td>
    <td>@GetInputType(Indexacion_Labels.Input_Type, Indexacion_Labels.Name)</td>
</tr>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-07
    • 2011-04-06
    • 2019-03-20
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多