Can I make razor recognize .html file extension as its own? - asp.net-mvc

So I can use the designer mode? I'm relying less on asp.net mvc html helpers, but not totally ditching it, opting to use plain html (in which should have no problem being rendered in Design Mode) instead
Is this possible?

Write you own View Engine
public class MyRazorViewEngine : RazorViewEngine
{
public MyRazorViewEngine()
{
base.AreaViewLocationFormats = new string[]
{
"~/Areas/{2}/Views/{1}/{0}.html",
"~/Areas/{2}/Views/Shared/{0}.html",
};
....
See System.Web.Mvc.RazorViewEngine for the rest of the locations to include
Then register it on startup
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyRazorViewEngine()));
RazorCodeLanguage.Languages["html"] = new CSharpRazorCodeLanguage();
and the following to your applications web.config
<system.web>
<compilation debug="true" targetFramework="4.5" >
<assemblies>
<add assembly="System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
<buildProviders>
<add extension=".html" type="System.Web.WebPages.Razor.RazorBuildProvider, System.Web.WebPages.Razor"/>
</buildProviders>
</compilation>
</system.web>
Upside - you get designer mode, Downside - you lose all razor highlighting and intellisense

Related

Controller + View in a separate assembly - The name 'ViewBag' does not exist in the current context

To the mods: not a duplicate, other answers (mainly "check the web.config in the Views folder") didn't work.
I have a main asp.net MVC application which discovers controllers and views in a separate assembly: controllers with MEF and a custom ControllerFactory, views with a custom VirtualPathProvider which discovers the views embedded in the same (of the controller) assembly.
The discovery of both parts works good: the controller factory finds the controller and initializes it using Ninject, the VirtualPathProvider recognizes that it has to look for the view in the assembly and loads it.
The web.config in the Views folder of the separate assembly is the one VS2013 generated when creating a new asp.net mvc project:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Routing" />
<add namespace="Fos.WS.DemoCustomization" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.webServer>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
Controller:
public ActionResult Index()
{
var dll = "~/Plugins/" + this.AssemblyName; //"~/Plugins/" is to instruct the custom viewpathprovider to discover the view from the assembly
return View(dll + "/Fos.WS.DemoCustomization.Views.Demo.Index.cshtml");
}
View:
#{
ViewBag.Title = "Demo";
}
<h2>Hi, Demo</h2>
The error i keep getting is
Compiler Error Message: CS0103: The name 'ViewBag' does not exist in the current context
Source Error:
Line 38: public override void Execute() {
Line 39:
Line 40: ViewBag.Title = "Demo";
Line 41:
Line 42: BeginContext("~/Plugins/Fos.Ws.DemoCustomization.dll/Fos.WS.DemoCustomization.Views.Demo.Index." +
Source File: c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\482869c5\3f1d4579\App_Web_fos.ws.democustomization.views.demo.index.cshtml.41ce77d0.bg7gacz2.0.cs Line: 40
Thanks
Edit: tried to remove the viewbag part and keep just the , now the error is different:
The view at '~/Plugins/Fos.Ws.DemoCustomization.dll/Fos.WS.DemoCustomization.Views.Demo.Index.cshtml' must derive from WebViewPage, or WebViewPage.
It looks like the web.config isn't there.
Answers a little late, but I think I may be able to add a bit of insight. So i haven't worked in this exact scenario, but i have worked with MEF, and dynamic View rendering separately.
Obvious
So an obvious issue if i'm reading your setup correctly is you're relying on that web.config defined above but it is in the remote assembly. I don't believe your IOC containers are able to access the assembly definitions from the remote config.
You even recognize that it is not picking up the web config values in your question. I know you said you had tried other web config resolutions without success, but I think that will be your best bet because it needs to pull in those definitions somehow, and trying to define those manually is going to be a hack.
Less Obvious
The reason you're seeing those exceptions is the ViewData object is defined by the WebViewPage base class, your config as you can see defines that as your base class for all views. without that base class, it's not a view and not parsable.
The reason I think it was hiding this error when accessing the ViewBag explicitly is the ViewBag is a wrapper in the ViewContext, passing ViewData to a DynamicViewDataDictionary. The ViewContext won't build if you pass in null ViewData, I think by calling the ViewBag explicitly on a null ViewContext it was just blowing up earlier in the chain, or rather the compiler recognized the issue this way.
Utility Helper
Since I am sorry I can't offer a silver bullet for this issue. Just more info pointing to the web.config not pulling in. I'm going to add a fun helper, that is also a hack for getting remote/dynamic Razor Views to parse manually from a file. You can also use this to make sure remote Views are well formatted and see how they will output. If you plugged this in I bet since it's defining a RazorView which manages the WebPageView initialization in this case. It'll work for your remote Views. worth noting this is a hack and not ideal for handling all of your View Rendering but is certainly handy in some sticky corner cases.
using System.IO;
using System.Web.Mvc;
namespace Utils
{
public class RazorUtility
{
/// <summary>
/// Takes a file path to a Razor View and a controller context and renders the the View to a string
/// </summary>
/// <param name="path">file path to view</param>
/// <param name="context">controller context to render against</param>
/// <returns></returns>
public static string RenderView(string path, ControllerContext context)
{
//You need to include the Model in the ViewDate of the context passed in.
var st = new StringWriter();
var razor = new RazorView(context, path, null, false, null);
razor.Render(new ViewContext(context, razor, context.Controller.ViewData, context.Controller.TempData, st), st);
return st.ToString();
}
}
}

ASP.NET Views: Avoiding using <%# Assembly... in every .aspx

Virtually every .aspx page I have in my web site needs to have this at its top to function correctly:
<%# Assembly Name="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
Is there anyway I can avoid having to declare this in the .aspx view for every page? Isn't there some way I can declare this globally for all .aspx views? Maybe something in the web.config?
Add it to assemblies
<assemblies>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
The #Assembly directive correspond to assemblies tag in web.config not namespace tag. Check MSDN reference
You can declare it in web.config in the assemblies section, like this:
<system.web>
<compilation>
<assemblies>
<add assembly="System.Web.Mvc, Version=3.0.0.0 ... "/>
</assemblies>
</compilation>
</system.web>
However, according to the MSDN docs:
Assemblies that reside in your Web application's \Bin directory are automatically linked to ASP.NET files within that application. Such assemblies do not require the # Assembly directive. You can disable this functionality by removing the following line from the section of your application's Web.config file:
<add assembly="*"/>
As others have pointed out, you can declare this in the web.config pages section.
Another alternative (if its available to you) is to use the new Razor View engine. It not only removes this type of code, but also provides cleaner, overall syntax. Of course, I realize this may not be a viable solution as you may be limited by your current technology/customer needs/etc.
An example of what you may see at the top of a Razor page is shown here:
#model Some.StronglyTyped.Model
#using Other.Libraries.To.Import
#{
ViewBag.Title = "Specific Page Title";
}
Put it in the Web.config as a global namespace. It will be available to all your pages there.
<system.web>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web>

MEF and Razor Views inside Class Library

I have a composite ASP .NET MVC 3 Razor application using MEF. Everything goes fine if I am to deploy plugins as DLL files and views (CSHTML) under the regular Views folder from the application. But this is not very clean and it won't be a real plugin if I don't place views as embedded resources within the DLL files (along with both controllers and models).
I've followed many articles (most of them are outdated). In fact there is one quite good one here on Stack Overflow: Controllers and Views inside a Class Library
I've also checked docs for VirtualPathProvider and I've been able to build a custom one that finds the file within the assembly and loads it perfectly (or at least gets the stream to it). For this I've followed the VirtualPathProvider documentation on MSDN.
There is also an implementation for VirtualFile but not yet for VirtualDirectory.
Here is the problem. I'm working with Razor views. I do know that they need config specs from the web.config file for Razor to build them. But if I embed them within the DLL this config is simply lost.
I wonder if that's why I keep getting the error:
The view at '~/Plugins/CRM.Web.Views.CRM.Index.cshtml' must derive
from WebViewPage, or WebViewPage.
Maybe I just need to add some code to make it work? Any ideas?
My preferred way to embed Razor Views in a Class Library is to copy them into the MVC website's Views/Areas folders with a post build event. Custom view locations can be specified if you override the ViewEngine or VirtualPathProvider.
The tricky part for me was getting intellisense to work in these View Class libraries. First, you must add a Web.Config to your View assembly. Note that you don't have to actually include it in your assembly. It only has to be in the assembly root directory (or views folder). Here is an example. Regard the important Assemblies/Compilation section.
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<compilation targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
Next, you need to modify your class library's vbproj file so that all OutputPath elements point to 'bin\' instead of 'Debug\bin\' or 'Release\bin\'. This is the main difference I found between class libraries and ASP.Net web project types that can cause intellisense bugs.
If you still recieve your must inherits error, consider using #Inherits System.Web.Mvc.WebViewPage in your views. If you are not copying your views into your website project, you may be loading them from Embedded Resources using a custom ViewEngine / VirtualPathProvider. If that is the case, you definately need the Inherits so Razor knows what your view base class is unfortunately.
Good luck.
You might take a look at the following blog post.
Hossam,
The post you're talking about is what Darin has already suggested. The main down side to that approach is using the custom MvcRazorClassGenerator compiler to convert the CSHTML view files in to class files. To do so you have to set every CSHTML view in your project to Content and set the Custom Tool to MvcRazorClassGenerator.
I can't speak for LordALMMa but I did download the compiler source and gave it a shot and it doesn't exactly work the way I was hoping.
My other approach was to include the CSHTML files as Embeded Resources in the external DLL, read in the raw contents of the file and execute the view as a string (See the RazorEngine on CodeProject for an example: http://razorengine.codeplex.com/)
I didn't want to fully depend on the RazorEngine in an enterprise application because I don't know how well it is compatiable with all of the Razor syntax so I gave up on that for now.
I'm coming from a prototype I built in ASP.NET MVC 2.0 that is a multi-tennant application. On a server farm we have one instance of an application running where all clients share the same code base. In my MVC 2.0 prototype I was able to determine what "client" the request was being made for, check for a custom controller that over-rides the base (for customizations of the core code) and also check for custom views (for customizations of the core view). What this does is allow us to deploy a "plugin" per say for each client. The software detects if the client has a custom controller that matches the request as well as a custom action that matches and if it does, it uses the customized controller/action instead.
When I started migrating my prototype to MVC 3 I ran in to the same problem as LordALMMa, the error "The view at '...Index.cshtml' must derive from WebViewPage, or WebViewPage". I'll look in to placing "#inherits System.Web.Mvc.WebViewPage" on my CSHTML views and see if that gets me any closer to getting it to work.
Since I have a working MVC 2.0 prototype using MVC 3 Razor is not a top priority and I don't waste a ton of time on it. I'm sure I can port the MVC 2.0 to MVC 3.0 using the WebForms engine if we need to leverage the 4.0 Framework.
Hey I suspect you have good reasons for wanting views inside DLLs. However also consider that it is an unusual way of packaging everything into one entity.
If you are developing a plugin, these days people opt for packaging in the NUGET format, which also solves your kind of problem among other things. It has a .nupkg structure which is also one way of distributing plugins as packages and libraries.
Another solution which communities generally follow is (if they do not want something as elaborate as nuget) they code up the plugin DLLs such that, it does not use view engines like razor, instead outputs HTML all by itself using the old primitive way of Response.Write and thus become independent of cshtml files. If you still want to use cshtml - see this blog entry for precompiling those into classes.

MVCContrib Portable Area No Intellisense for ViewPage<T>

I am trying out portable areas using MVCContrib.
In general these work well and it seems to be a good way to share controllers\views between web projects.
The only problem that I'm having is that Intellisense (specifically, for the HtmlHelper) is not working in the view for strongly typed views i.e. ViewPage.
The intellisense does work however when the view is a plain 'ol System.Web.Mvc.ViewPage
A similar questions has been asked here:
MvcContrib Portable Areas View Intellisense?
But these suggestions don't seem to make any difference.
I am using MVC 2, the portable areas are in their own class library as in the MVCContrib sample code.
I'd also like to add that the MVC sample code gives me the same behaviour, if I change the sample project to make the view page strongly typed then intellisense stops working.
Are other people having the same problem ?
Does anyone know the cause and or solution ?
the web.config from my Views folder is as follows:
<?xml version="1.0"?>
<configuration>
<system.web>
<httpHandlers>
<add path="*" verb="*"
type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>
</handlers>
</system.webServer>
</configuration>
This was a problem with ReSharper intellisense in VS2010, ReSharper v5.0.
If I change my ReSharper options (ReSharper->Options->Intellisense->General) to use Visual Studio intellisense then it works!!

Crystal Reports Images and ASP.Net MVC

I am having trouble with Crystal Reports when using charts and images which use CrystalImageHandler.aspx. The image cannot display and I suspect this is due to a problem with MVC routing.
The path image path is similar to this:
src="/CrystalImageHandler.aspx?dynamicimage=cr_tmp_image_a8301f51-26de-4869-be9f-c3c9ad9cc85e.png"
With the URL similar to this:
localhost:01234/ViewCrystalReports.aspx?id=50
The image cannot be found prumably because it's looking in a non-existant directory. How can I change the path CrystalImageHandler.aspx is located at? I think if I were to reference from the root the problem would be solved but anything I change in Web.Config fails to work.
I should mention this is on a conventional aspx page, not a view etc
I solve this problem editing Web.Config file
Insert the following line:
<system.web>
...
<httpHandlers>
<add path="CrystalImageHandler.aspx" verb="GET" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"></add>
</httpHandlers>
...
*take care with write your number version (Version=xx.x.xxxx.x)
Figured it out. The routing was interfering with the CrystalImageHandler.aspx link that was being generated. Global.aspx has the following line to tell the routing engine to ignore resource files:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
but this isn't a conventional resource file, it's an aspx file for some reason (anyone know why?)
adding this fixed it:
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
public class CrystalImageHandlerController : Controller
{
//
// GET: /Reports/CrystalImageHandler.aspx
public ActionResult Index()
{
return Content("");
}
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
var handler = new CrystalDecisions.Web.CrystalImageHandler();
var app = (HttpApplication)filterContext.RequestContext.HttpContext.GetService(typeof(HttpApplication));
if (app == null) return;
handler.ProcessRequest(app.Context);
}
}
This controller will invoke the handler. Just add a route to this as CrystalImageHandler.aspx, it can also be used with any sub path you'd like (in this case /reports). Something I could NEVER get the handler to do via configuration.
To view in local machine,you will add the following code in web config
<httpHandlers>
<add verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web,Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" />
</httpHandlers>
...............................
<appSettings>
<add key="CrystalImageCleaner-AutoStart" value="true" />
<add key="CrystalImageCleaner-Sleep" value="60000" />
<add key="CrystalImageCleaner-Age" value="120000" />
</appSettings>
The following code is for displaying in server
<system.webServer>
<handlers>
<add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=10.2.3600.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/>
</handlers>
</system.webServer>
:) I will solve that problem in adding in web config
It's because the routing was interfering with the CrystalImageHandler.aspx. So either in Global.asax or routeConfig file we can ignore route for .aspx extension files. You can ignore .aspx extension route by adding following line.
routes.IgnoreRoute("{allaspx}", new {allaspx=#"..aspx(/.*)?"});

Resources