Skip ViewBag as parameter

If I have a value inside a dynamic ViewBag , why can't I pass it to a method? So for simplicity, let's say I have a ViewBag.SomeValue , and I want to pass the ViewBag.SomeValue to an HTML helper. If the HTML helper accepts a dynamic variable, why doesn't 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); } 
+6
source share
3 answers

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

Consider the following console application example that 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 quit:

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

Actually, since Adam said you need to use a strongly typed view model and never use a ViewBag. This is just one of the millions of reasons why the ViewBag should not be used.

+8
source

More importantly, the ViewBag is some bad practice of using because of the magic lines as properties in the viewbag - what you are trying to send to it. Maybe there is a better way? You should be able to use a helper instance to reference it through:

helper.ViewContext.Controller.ViewBag

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

+3
source

I know this is an older question, but this is what occurred to me when I was looking for this problem.

It's easy enough to pass the ViewBag as a parameter by simply listing it as a dynamic method. For example, this is how I pass the ViewBag to one of my helper classes for sorting columns.

 public static IEnumerable<Models.MyViewModel> MyMethod(IEnumerable<Models.MyViewModel> model, string sortOrder, dynamic ViewBag) 
0
source

Source: https://habr.com/ru/post/903352/


All Articles