2

Can I make extension methods for ViewBag, or I should use ViewData instead?

I tried creating extension methods for object since that is ViewBag's type, but it didn't work.

public static void AddUserData(this object ViewBag)
{

}

Can someone please explain why we can't have extension methods for ViewBag?

Rahul Nikate
  • 5,954
  • 5
  • 38
  • 51
Akbari
  • 2,299
  • 7
  • 39
  • 81

1 Answers1

4

Because the ViewBag is a dynamic type, extension methods will not be picked up on their properties without casting to the appropriate type first.

I recommend you to reduce use of ViewBag to avoid having to cast everywhere. Instead you can use strongly typed view models for views.

Rahul Nikate
  • 5,954
  • 5
  • 38
  • 51