MVC How to use IEnumerable variables stored in ViewBag in a view?

The following is simplified code where an error occurs in the 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 the error occurs
        @Html.Partial("EmployeeDisplayControl", ViewBag.ITDept[i])
    }
    <br />
}

There @Html.Partial("EmployeeDisplayControl", ViewBag.ITDept[i])is an exception in the line :

'System.Web.Mvc.HtmlHelper>' does not have an applicable method named "Partial", but it seems to have an extension method using this name. Extension methods cannot be dynamically sent. Think about how to use dynamic arguments or invoke an extension method without extension method syntax.

I suppose this suggests that I cannot use extension methods in dynamic expression, is there any workaround for this ??

I made a fiddle for this error: https://dotnetfiddle.net/ekDH06

+4
3

/:

public class YourViewModel
{
   public IList<Employee> ITDept {get; set;}
   public IList<Employee> Officers {get; set;}
   //other properties here
}

Employee ( Views/Shared/EditorTemplates Views/Shared/DisplayTemplates):

(, ):

@model EnrolSys.Models.Employee

<div>
   @Html.EditorFor(m=>m.Name)
</div>

YourViewModel :

@model YourViewModel 


@using (Html.BeginForm("Save", "EmployMaster"))
{
    <div>
        @Html.EditorFor(m=>m.ITDept)
    </div>
}
+2

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

, .

: "", "foreach":

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

, ViewBag.ITDept IEnumerable<Employee>.

+6

You need to put a static type for a dynamic expression. Try the following:

@Html.Partial("EmployeeDisplayControl", (object)ViewBag.ITDept[i])
+1
source

Source: https://habr.com/ru/post/1589421/


All Articles