Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC How to use IEnumerable variables stored in ViewBag in the View?

Below is the simplified code where the error occurs in View:

Model:

    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);
    }

View:

@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 />
}

In the line @Html.Partial("EmployeeDisplayControl", ViewBag.ITDept[i]), there's an exception:

'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.

I guess it's saying I can't use extension methods in dynamic expression, is there any workaround for this??

I've Made a Fiddle for this error: https://dotnetfiddle.net/ekDH06

like image 658
User2012384 Avatar asked Jan 09 '23 08:01

User2012384


1 Answers

When you use

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

you get an IEnumerable in Viewbag.ITDept, not an IList. That means you can't use an indexer (like ViewBag.ITDept[i]), as an IEnumerable doesn't support random access.

One solution:

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

now it is a List, so you can use an indexer.

Other solution: do not use a "for" loop, but a "foreach":

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

Maybe you still need to cast that ViewBag.ITDept to IEnumerable<Employee>.

like image 150
Hans Kesting Avatar answered Jan 23 '23 17:01

Hans Kesting