错误:以下方法或属性之间的调用不明确

时间:2016-12-16 09:08:44

标签: asp.net-mvc razor

我收到此错误:

  

以下方法或属性之间的调用不明确:

     

DisplayNameFor< IEnumerable< Category&gt ;, string>(HtmlHelper< IEnumerable< Category>&gt ;,System.Linq.Expressions.Expression< System.Func< IEnumerable,string>>)

     

     

DisplayNameFor< Category,string>(HtmlHelper< IEnumerable>,System.Linq.Expressions.Expression< System.Func< Category,string>>)

我的模特是

public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
}

我的上下文模型是

public class CategoryContext : DbContext
{
    public DbSet<Category> category { get; set; }
}

我的控制器是:

public ActionResult GetCategory()
{
    using (CategoryContext cc = new CategoryContext())
    {
        var cat = cc.category.ToList();
        return View();
    }
}

我的观点是:

@model IEnumerable<CRUD_Manav_EF.Models.Category>

<h1>Get Category</h1>

<table>
    <tr>
        <th>@Html.DisplayNameFor(model => model.CategoryName)</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayNameFor(modelItem => item.CategoryName) // I get error here
            </td>
            <td>
                @Html.ActionLink("Edit", "Update", new { id = item.CategoryId })
                @Html.ActionLink("Details", "Details", new { id = item.CategoryId })
                @Html.ActionLink("Delete", "Delete", new { id = item.CategoryId })
            </td>
        </tr>
    }
</table>

1 个答案:

答案 0 :(得分:0)

显示此错误是因为您已使用过  表foreach循环中的@Html.DisplayNameFor(model => model.CategoryName)和调用在上面提到的那些方法之间是不明确的。由于迭代时反复使用显示名称没有任何好处。如果您将看到@Html.DisplayNameFor()的完整描述,您将得到第一个参数仅接受模型(lambda表达式)而不接受模型的IEnumerable。这也会在您的编译器错误中显示。

参见示例截图(这是虚拟项目)

enter image description here

在foreach循环中使用@html.DisplayFor(..)

@foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.CategoryName)
            </td>
            <td>
                @Html.ActionLink("Edit", "Update", new { id = item.CategoryId })
                @Html.ActionLink("Details", "Details", new { id = item.CategoryId })
                @Html.ActionLink("Delete", "Delete", new { id = item.CategoryId })
            </td>
        </tr>
    }

这个htmlhelper方法将采用你的模型的IEnumerable。并且您的问题将得到解决(您可以自己检查)。