How to make intellisense works with RazorEngine?

11.6k views Asked by At

I am trying to configure RazorEngine so that intellisense works on views. I add RazorEngine and Microsoft.AspNet.Mvc using nuget. I create TestView.cshtml and declare @model MyModel but it says The name 'model' does not exist in the current context. I also cannot use intellisense inside the view.

Do I miss any step here? How to enable intellisense in the View?

3

There are 3 answers

3
matthid On

You can use

@using RazorEngine.Templating
@using Namespace.Of.My.Model
@inherits TemplateBase<MyModel>

on the top of your template.

This works fine on a new Console Application with Visual Studio 2013 (after adding a reference to RazorEngine). The documentation for this is here.

EDIT:

I noticed that this only works when the RazorEngine project is added to the solution and directly referenced. If you use the NuGet package you additionally need to ensure one of the following to make it work:

  1. Your project output path is set to bin\ instead of bin\Debug\ and bin\Release\.
  2. Copy RazorEngine.dll and System.Web.Razor.dll to bin\
0
FLCL On

Oh, I faced with such problem while adding Razor Engine to my custom dll project. To solve this you have to:

1.correctly setup namespaces in web config file(hope you have it in views folder, if not - copy from MVC project):

 <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.Routing" />       
    <add namespace="System.Web.Optimization" />
  </namespaces>
</pages>
</system.web.webPages.razor>
...

2.use to build into bin\ path(not any other, you may use copy post-build command to move results to another place)

3.clean solution and remove obj and bin folders, than build

My views' code starts from @model MyModelClass and all works fine

7
Zachary Dow On

I know this question is kind of old. I could not get anything to work, no matter the solution. I have a hack fix that may be palatable to some. I don't like it very much, but it's the most usable thing I've gotten so far.

The trick is to define the "Model" yourself as a variable from the actual Model. I defined it as "TrueModel", but whatever name you can think of that doesn't collide with "model" or "Model" should work. Then just replace all of your instances of "Model" with "TrueModel".

@using Namespace.To.My.Models
@* This line should still look like an error, 
   but we only really care about the intellisense in the rest of the .cshtml file. *@
@{ ModelType TrueModel = (ModelType)Model; }

<div>
@TrueModel.MyProperty is here now.
</div>
<p> @TrueModel.MyOtherProperty is great! </p>

It's not a great solution, but it might be useful.