Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share HTML between ASP.NET MVC4 projects

I have a couple of websites I am building that display the same or similar data in pages. To reduce code duplication, what i did was created a 3rd project/website and figured I'd use that as the location for shared HTML, java-script, CSS, images, etc.

I am able to include JavaScript, CSS, and images fine from the shared project using relative paths. however i am not able to render partial pages of HTML. when trying to access the two websites that are trying to load partial page using code like this:

@RenderPage("/SharedArtifacts/Views/MySharedViewscshtml")

I get the following response:

The virtual path '/SharedArtifacts/Views/MySharedViewscshtml' maps to another application, which is not allowed.

Now I've googled and tried using ~ prefix to specify the root of the path to solve the problem, but to no avail... still the same error.

Any thoughts on how to resolve this issue?

like image 912
mike01010 Avatar asked Oct 23 '15 03:10

mike01010


2 Answers

We do this all the time. The simple (non-programming) way is to create virtual folders in IIS that map to a shared folder common to all the companion sites. We commonly do this for error result pages and other generic content.

/Views/SharedVirtual/somefile.ascx

The path /Views/SharedVirtual is mapped via IIS's virtual folders. Then in controllers we can do a return View("/Views/SharedVirtual/somefile.ascx",somemodel);. It also works with RenderPartial as well.

Locally when working with the projects I use mklink to create a junction point in the project folder that maps to the shared common folder. That way VS thinks the folder is local when its not and can run the project locally for debugging.

We typically don't use Razor but the concept should work just the same since its not VS that is doing the share mapping, its the OS and IIS that is.

One caveat is that if you edit the views, they will change in all projects so you must be careful with your edits so ensure they will be compatible when used across all the projects that reference them.

like image 124
Wolfie Avatar answered Oct 03 '22 02:10

Wolfie


Views you want rendered reside outside the web app root. This is not allowed at least for security reasons.

What you can do, however, is embed the veiws (.cshtml) as resources by selecting "Embed as Resource" build action instead of the default one. Then, using NuGet package manager install and use a Virtual Path Provider capable of rendering the already embedded views like here, here, or here.

like image 33
Alexander Christov Avatar answered Oct 03 '22 04:10

Alexander Christov