c# - MVC 如何在View中使用保存在ViewBag中的IEnumerable变量?

标签 c# asp.net-mvc asp.net-mvc-4

下面是View中出现错误的简化代码:

型号:

    public class Employee
    {
        public string EmployeeID{ get; set; }
        public string Name { get; set; }
        ...
    }

Controller :

    public ActionResult Index()
    {
        var model = selectAllEmployees();
        ViewBag.ITDept = model.Where(a => a.departmentID == 4);
        ViewBag.Officer = model.Where(a => a.departmentID == 5);
        return View(model);
    }

查看:

@model IList<EnrolSys.Models.Employee>

@{
    Layout = null;
}

@using (Html.BeginForm("Save", "EmployMaster"))
{
    for (int i = 0; i < ViewBag.ITDept.Count(); i++)
    {
        //Here's the error occurs
        @Html.Partial("EmployeeDisplayControl", ViewBag.ITDept[i])
    }
    <br />
}

@Html.Partial("EmployeeDisplayControl", ViewBag.ITDept[i]) 行中,有一个异常:

'System.Web.Mvc.HtmlHelper>' has no applicable method named 'Partial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

我猜是说我不能在动态表达式中使用扩展方法,有什么解决方法吗??

我为这个错误做了一个 fiddle : https://dotnetfiddle.net/ekDH06

最佳答案

当你使用

ViewBag.ITDept = model.Where(a => a.departmentID == 4);

你得到一个 IEnumerableViewbag.ITDept ,不是 IList .这意味着您不能使用索引器(如 ViewBag.ITDept[i] ),因为 IEnumerable 不支持随机访问。

一个解决方案:

ViewBag.ITDept = model.Where(a => a.departmentID == 4).ToList();

现在它一个列表,因此您可以使用索引器。

其他解决方案:不使用“for”循环,而是使用“foreach”:

foreach (var employee in ViewBag.ITDept)
{
    @Html.Partial("EmployeeDisplayControl", employee )
}

也许您仍然需要将 ViewBag.ITDept 转换为 IEnumerable<Employee> .

关于c# - MVC 如何在View中使用保存在ViewBag中的IEnumerable变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30395438/

相关文章:

c# - MSBuild 任务不会导致编译生成的 c# 文件

asp.net-mvc - ASP.NET Web Api 元数据交换?

javascript - amCharts 的 JS 图表折线图中的随机曲线

c# - 为什么 Visual Studio 的 MVC 模板在 View 中而不是在相应的 Controller 中设置 ViewBag.Title?

c# - 使用匿名类型列表填充 AutoCompleteBox

c# - 根据文件名选择数千个文件

c# - 如何检测 WCF 流客户端是否断开中流

c# - 与 asp.net MVC 中的 Controller 名称不同的 url

c# - ASP.NET MVC5 路由注释 MS_DirectRouteMatches

c# - EF MVC4 C# : Many to Many Relationship with "relationship property" DB First