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
  • 6,192
  • 5
  • 42
  • 54
Akbari
  • 2,369
  • 7
  • 45
  • 85

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
  • 6,192
  • 5
  • 42
  • 54