ASPMVC Integration

From NDjango
Jump to: navigation, search


To integrate NDjango as a view engine for ASP.MVC you'll need to add a reference to the NDjango.ASPMVCIntegration40 or NDjango.ASPMVCIntegration35 assembly and make a small change to your Global.asax.cs:

  • Add a public member called DjangoTemplateManager:

<source lang="csharp"> public class MvcApplication : System.Web.HttpApplication { public NDjango.Interfaces.ITemplateManager DjangoTemplateManager { get; set; }

... } </source>

  • Add the following line inside Application_Start method

<source lang="csharp"> protected void Application_Start() { ...

ViewEngines.Engines.Insert(0, new NDjango.ASPMVC.DjangoViewEngine()); } </source>

You can also easily plug in your own tag library as it is shown below:

<source lang="csharp"> protected void Application_Start() { ...

ViewEngines.Engines.Insert(0, new NDjango.ASPMVC.DjangoViewEngine( pr => pr.WithLibrary("ASPMVCSampleLibrary.NDjangoExtension40") )); } </source>

... aand that's it. This will register the NDjango ASPMVC View Engine, and allow you to both infer view paths from controllers (standard behavior), and specify explicit template paths via ViewResult View(string viewName); instead of ViewResult View();. ".django" extension must be omitted.

Implementation note
To track the official django implementation, session values are exposed to the django context unqualified. That means that if your ViewData has a value named foo and so does your session, the NDjango integration will throw a runtime exception notifying you of the collision. This is a construct that ASP.MVC allows, and NDjango does not.
Implementation note
The asp.mvc-specific format of the {% url %} tag is as follows: {% url action_expr [controller_expr] [as name] %}, where action_expr is an expression (string literal or variable) that returns a valid action, and controller_expr is an optional expression that returns a controller name. These values are then fed into UrlHelper.Action(action[, controller]), e.g. - {% url "index" "home" as v %} {{ v }}, which will yield /virtualDir/home/index

You can also use 'action-link' tag which works the same as the standard Html.ActionLink method. This tag is defined in ASPMVCSampleLibrary.NDjangoExtension40.dll library which is provided with the NDjango setup.