Is it possible to declare a function or helper in a Razor layout view and have a child Razor view use that function? My structure is :
_layout.cshtml -> index.cshtml
Where index.cshtml uses _layout.cshtml as its layout. This is the default structure.
I want to be able to place common functions/helpers in _layout.cshtml and refer to them in index.cshtml and all other views that use _layout.cshtml. It doesn’t work out of the box unless I’ve missed something.
I know. I should be using compiled AppHelpers or HtmlHelpers for this, but I can foresee a great convenience in being able to tweak select functions/helpers directly in a _layout.cshtml file.
Thanks
No, that’s not possible.
@functionsare visible only inside the current view.You could use
@helperwhich could be placed inside theApp_Codefolder and be reused from all views.For example you define
~/App_Code/MyHelpers.cshtml:and then in some view:
But I would recommend compiled helpers. They are unit test friendly and view engine agnostic and when tomorrow Microsoft reveal their brand new Blade view engine you will have 0 work to do in order to use them, whereas if you code against Razor specific things like
@functionsand@helperyou will have to port them. Probably not a concern for you but worth mentioning.