下面是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);
你得到一个 IEnumerable
在Viewbag.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/