I am using asp.net MVC 4, I’d like to do something like this in my view
<a href=@NamespaceHere.StaticUtil.TheFunctionIUseAlot("/blah", 1, Viewbag, "link and view specific") class="thing">my link</a>
I don’t like it. Is there a way I can have the namespace implicit? Can I not pass in Viewbag and grab it somehow like global.request.current.viewbag?
If it helps I don’t need TheFunctionIUseAlot to be static. I just need it to be easily callable in all my views and hopefully i’d like to not pass in viewbag. The reason I pass viewbag is because i need something in the controller which i stuck in viewbag as well. Maybe i can put it in the model but i don’t want the same problem where i am passing model instead of viewbag
You can make the namespace implicit by adding
@using NamespaceHere;at the top of your view, or by registering it as a namespace in the views web config. Something like this:You can get access to the viewbag in your function if you use a custom page base type for your views. You can find instructions on doing that here: http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx.
In your situation, to get access to the ViewBag you will want to define your
FunctionThatIUseALotin a non-static class that takes a WebViewPage as a constructor parameter (either as dynamic or as a ViewDataDictionary). Then, in your WebViewPage’sInitHelpersoverride, you can create your helper class, passing inthis. That will give you access to all of the standard properties of the WebViewPage.Something like this:
The above is not everything you need to do to make it work, you will need to read the article for the rest. But the end result should be that you can just call
@Utils.FunctionThatIUseALot("some value")directly in your views.Note: you will need to do this twice – once for the standard
WebViewPagebase class, and one for theWebViewPage<TModel>base class.