Monday, November 17, 2014

Anonymous type in ViewBag getting model binder error MVC ASP.Net

 When I have pass the Anonymous type list in viewbag I am getting the error “[RuntimeBinderException: 'object' does not contain a definition for 'EmployeeName']” . When accessing the property it causes a runtime error because Anonymous types are internal, so Razor pages cannot access their properties. So I have created viewmodel to overcome this error. Here is example
 
public class GroupByClause
{
    public string EmpName { get; set; }
    public decimal salary { get; set; }
}
 
public ActionResult AggregateFunction()
        {
            List<Employee> EmployeeCollection = new List<Employee>();
            EmployeeCollection.Add(new Employee { id = 1, Name = "Anil Sharma", Address = "India", Salary = 12122, IsActive = true });
            EmployeeCollection.Add(new Employee { id = 12, Name = "abc", Address = "Usa", Salary = 12156, IsActive = true });
            EmployeeCollection.Add(new Employee { id = 3, Name = "xyzx", Address = "uk", Salary = 12676, IsActive = true });
            EmployeeCollection.Add(new Employee { id = 4, Name = "Anil Sharma", Address = "germany", Salary = 45455, IsActive = true });
            EmployeeCollection.Add(new Employee { id = 15, Name = "sdfd", Address = "India", Salary = 45467, IsActive = true });
            EmployeeCollection.Add(new Employee { id = 25, Name = "gg", Address = "India", Salary = 3445, IsActive = false });


            //simple query
         

            //lambda expression query
            var EmployeeScoring = EmployeeCollection.Where(x => (x.IsActive == true)).GroupBy(k => k.Name).
                Select(p => new
                {
                    EmpName = p.Key,
                    salary = p.Sum(x => x.Salary)

                }); //annonymus type and getting error
   //error resolved
            var EmployeeScoring = EmployeeCollection.Where(x => (x.IsActive == true)).GroupBy(k => k.Name).
                Select(p => new GroupByClause
                {
                    EmpName = p.Key,
                    salary = p.Sum(x => x.Salary)

                });

}

In view
<ul>
@foreach (var item in   ViewBag.EmployeeScoring  as List<GroupByClause>)
{
    <li><span>@Html.Raw(item.EmpName) </span> <span>@item.salary</span> </li>
}

</ul>

No comments:

Post a Comment

http://blogsiteslist.com