Share a razor declarative helper between multiple mvc web projects

1.6k views Asked by At

Let's say I have 2 MVC web projects (web1 and web2) and 1 project containing shared views (common) (using the razorgenerator of David Ebbo)
web1 and web2 both have a test.cshtml file. Several blocks of code in both test.cshtml files are exactly the same.
I'm trying to find out if it's possible to share a declarative helper (@helper) between several cshtml files which are in DIFFERENT projects. So putting a cshtml file in my App_Code does not help (I would need to have 1 in each web project, which is obviously not what I want).
I know I could create a bunch of shared partial views in my 'common' project, but it seems kinda overhead to create 20 cshtml files that each contains a very small portion of html.
I know I can create a standard helper method (static string GenerateAPieceOfHtml(this HtmlHelper helper, ....)), but there I loose the ease of writing html as you can do it in a cshtml file.

For a short while I thought I bumped into an answer that would allow me to do it. But as I wrote in a comment, that code did not compile for me.

I hope my question is clear :)

[Update]
As csharpsi asks in a comment.. I did try out the code from the other post, but it did not spit out any HTML for me. Since I started to think that that answer should probably do the trick since it has 13 upvotes, I decided to give it a second try..
Again I didn't get any output, but then I tried it a little bit different.. and success!
I was trying this (which doesn't spit out any html on the page):

@{ new Test().DoSomething(Model); }

This is the version that DOES WORK:

@{
  var html = new Test().DoSomething(Model);
  @html
}  

Other version that works:

@(new Test().DoSomething(Model))

What should I do with this question? Delete it? Write an answer myself?

1

There are 1 answers

4
rouen On

Why are you trying to use razor helper for this anyway ? Razor helpers are one-particular-viewengine hack, your application shouldnt rely on them on many places (even amongst different websites). In this case, be sure to use standard MVC way - HTML helper. These you can easily share between websites, for example you can make your own class library full of them.