[RESOLVED]Razor Helpers in MVC?

Is it possible to use Razor syntax helpers (defined in .cshtml files) in ASP.NET MVC?

I’ve found no shortage of resources on how to create helpers in ASP.NET MVC, but they all define their helpers in .cs files and manually build html strings, rather than simply letting me use formatted html from a .cshtml file.

As a very minimal example of what I want to accomplish, here’s a couple of .cshtml files:

Page1.cshtml:

<h2>Page 1</h2>
@MyHelper.GetBackLink()

MyHelper.cshtml:

@helper GetBackLink()
{
    @:@Html.ActionLink("Back", "Index")
}

Intellisense tells me in Page1 that "The name ‘MyHelper’ does not exist in the current context," so it’s possible this is just a matter of putting the right @using directive in Page1.cshtml, but I don’t know what namespace my helper methods live in.  Any
thoughts?

Yes you can. however to share it with multiple views, you will have to put MyHelper.cshtml in the App_Code folder.

and access it as @MyHelper.GetBackLink()

very good example by Scottgu for the same scenario can be found at,

http://weblogs.asp.net/scottgu/asp-net-mvc-3-and-the-helper-syntax-within-razor

Regards,

Chintan

*Please mark it as answer if appropriate*

if the MyHelper is a class, then in the view page you can use like:

@{

var helper = new MyHelper();

var testResult = helper.GetBackLink();

}
This simple will store the return value from the getBackLink into testResult and you can use the variable in the viewpage anywhere, 

@testresult.

hope this helps.

thanks

Thanks, Chintan.  One side effect of moving my helper into ~/App_Code/ was that that the standard Html helper stopped working.  For posterity, there’s a workaround in a StackOverflow post (http://stackoverflow.com/questions/4710853/using-mvc-htmlhelper-extensions-from-razor-declarative-views)
linked to in the footnote of Scott’s post.

Leave a Reply