Samuel
Samuel

Reputation: 12341

Shared declarative html helpers between projects in Asp.Net MVC

Is it possible to put the declarative html helpers in an assembly different than the application web project?

Currently, the only place where I know I can put my declarative html helpers is in the folder 'App_Code' of my application web project.

After a couple of months of development, I now have a lot of these declarative html helpers and the only one solution I have to shared it among all my projects is with a the very bad practice of 'Copy Paste Driven Development'.

Any other ways?

P.S.

Just not to be confused by the definition of what is declarative html helpers, here is a code sample to makes the difference compared to c# extensions that extend the System.Web.Mvc.Html type:

@using Microsoft.Web.Mvc.Html

@helper YesNoRadioButton(System.Web.Mvc.HtmlHelper html, string name, bool value, bool disable = false)
{
   @html.RadioButton(name, true, value, id: name.Replace(".", "_") + "_Yes", disabled: disable) @:Oui 
   @html.RadioButton(name, false, !value, id: name.Replace(".", "_") + "_No", disabled: disable) @:Non   
}

@helper YesNoRadioButton(System.Web.Mvc.HtmlHelper html, string name, bool? value, bool disable = false)
{
   @html.RadioButton(name, true, value.HasValue && value.Value, id: name.Replace(".", "_") + "_Yes", disabled: disable) @:Oui 
   @html.RadioButton(name, false, value.HasValue && !value.Value, id: name.Replace(".", "_") + "_No", disabled: disable) @:Non   
}

enter image description here

Upvotes: 5

Views: 1898

Answers (3)

Nacht
Nacht

Reputation: 3494

Yes it is possible, all I had to do was put @using at the top of my razor pages to reference the other assembly that had the Helper functions.

Or, if you want to save yourself adding this using at the top of lots of files, you can add the reference to your Web.config file that exists under your Views folder. You might have to close and re-open your razor pages to help Visual Studio acknowledge the new assembly reference.

Upvotes: 0

Ed Charbeneau
Ed Charbeneau

Reputation: 4634

I wrote an article that takes you through the steps required to make a HTML helper library. There is a full project example at the end which you can download from GitHub.

https://www.simple-talk.com/dotnet/asp.net/writing-custom-html-helpers-for-asp.net-mvc/

Upvotes: -1

Bhushan Firake
Bhushan Firake

Reputation: 9448

Make a class library of those helpers and then share it among projects.It will be better if you put your helpers in a custom created folder Helpers. This is what I do.

You can refer to this answer: Where shall I put my utilities classes in a ASP.NET MVC3 application?

Upvotes: 2

Related Questions