0

Consider the following code:

Controller:

 public ActionResult ShowMenu ()
        {
            if(Session["ID"] != null && Session["Ten"] != null && Session["User"] != null)
            {
                int id = (int)Session["ID"];
                ViewBag.user=  db.ChucNangs.Join(db.Chuc_Nang_Quan_Tris, x => x.ID, y => y.MaChucNang, (x, y) => new {Ten = x.Ten, DuongDan = x.DuongDan,Icon= x.Icon, TrangThai = x.TrangThai }).Where(x=>x.TrangThai == true).ToList();
                return PartialView("_menu_right");
            }
            return RedirectToAction("Logout");
        }

enter image description here

I have an object of type Anonymous, and although there is data, it still displays an error.

How can I prevent this error?

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
Phan Phu
  • 13
  • 4

2 Answers2

0

You cannot use an anonymous type to pass data from action method to view, via ViewBag.

Create a view model class to represent this data you want to pass.

public class YourVm
{
    public string Ten { set; get; }
    public string DuongDan { set; get; }
    public string Icon { set; get; }
    public string TrangThai { set; get; }
}

and in your LINQ expression, do the projection using this view model instead of anonymous type.

 new YourVm {  Ten = x.Ten, 
               DuongDan = x.DuongDan,
               Icon= x.Icon, 
               TrangThai = x.TrangThai })
Shyju
  • 214,206
  • 104
  • 411
  • 497
0

You can not do that. Just make your life easier and create a view model class with all the properties you need. Check this one:

Stuffing an anonymous type in ViewBag causing model binder issues

Selvirrr
  • 146
  • 7