Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass the ViewBag as a Paramerter

If I have a value inside the Dynamic ViewBag, why can't I pass it to a method? So for simplicity's sake, lets say I have ViewBag.SomeValue, and I want to pass the ViewBag.SomeValue to an HTML Helper. If the HTML helper accepts dynamic as a variable, why wont it accept my ViewBag.SomeValue?

@Html.SimpleHelper(ViewBag.SomeValue)

public static string SimpleHelper(this HtmlHelper html, dynamic dynamicString)
{
    return string.Format("This is my dynamic string: {0}", dynamicString);
}
like image 452
TYRONEMICHAEL Avatar asked Dec 08 '11 06:12

TYRONEMICHAEL


2 Answers

As the error message tells you, extension methods cannot be dynamically dispatched. It's just not supported in .NET. It has nothing to do with ASP.NET MVC or Razor. Try writing an extension method to some type that takes a dynamic argument and then try invoking this extension method passing it a dynamic variable and you will get a compile time error.

Consider the following console application example which illustrates this:

public static class Extensions
{
    public static void Foo(this object o, dynamic x)
    {
    }
}

class Program
{
    static void Main()
    {
        dynamic x = "abc";
        new object().Foo(x); // Compile time error here
    }
}

So you need to cast:

@Html.SimpleHelper((string)ViewBag.SomeValue)

Actually, as Adam said you need to use strongly typed view model and never use ViewBag. It's just one of the millions of reasons why ViewBag shouldn't be used.

like image 95
Darin Dimitrov Avatar answered Nov 14 '22 22:11

Darin Dimitrov


Even more importantly since ViewBag is somewhat of a bad practice to use because of magic strings as properties on viewbag - what are you trying to send to it. Maybe there is a better way? You should be able to use the helper instance to reference it via:

helper.ViewContext.Controller.ViewBag

but I'm not one for using ViewBag except only for Title http://completedevelopment.blogspot.com/2011/12/stop-using-viewbag-in-most-places.html

like image 39
Adam Tuliper Avatar answered Nov 15 '22 00:11

Adam Tuliper