3

I am writing an AngularJS directive that uses a templateURL i.e.

m.directive('mySavingIndicator', function () {
    return {
        restrict: 'E',
        templateUrl: '/views/templates/savingindicator.html'
    };
});

I have created a plain old .html file within the views/templates directory but everytime I run this code MVC throws a null reference exception like its trying to find a controller for it (which doesnt exist). How do I stop MVC trying to treat this as a cshtml file, or how do I make it treat it as a cshtml file but not require a controller? It seems wasteful writing a controller just for these small templates?

2 Answers 2

4

MVC normally prevents any content files from being served from the Views folder (the Views folder is special).

However, you can change this by tweaking your web.config.

Change this:

<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode"    type="System.Web.HttpNotFoundHandler" />

To this:

<add name="BlockViewHandler" path="*.cshtml" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />

Example:

<handlers>
  <add name="JavaScriptHandler" path="*.js" verb="*"
     preCondition="integratedMode" type="System.Web.StaticFileHandler" />      
  <add name="HtmlScriptHandler" path="*.html" verb="*"
     preCondition="integratedMode" type="System.Web.StaticFileHandler" />
  <remove name="BlockViewHandler"/>
  <add name="BlockViewHandler" path="*.cshtml" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>

That way, only cshtml files are blocked from being served directly (html files are left alone).

Sign up to request clarification or add additional context in comments.

3 Comments

This looks promising! I dont have this line yet, what section would it be in?
This doesnt seem to work, I get errors about name being invalid and preCondition. If I remove these nothing works. I might, however, move my templates into another folder to work around this. Thanks
If I move the file outside of views, either to the root MVC folder or Scripts I can access the file directly but everytime Angular tries to load it I get 400 bad request. Why might this be happening?
0

I think the easiest way is to add IgnoreRoute in RouteConfig.

routes.IgnoreRoute("views/templates/savingindicator.html");

1 Comment

Can I make it ignore that entire folder?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.