Search code examples
asp.net-mvcwebsharper

How do you integrate Websharper with an existing ASP.NET MVC project?


The Websharper website has a tutorial on integrating ASP.NET with Websharper, but it is vague on certain things. I have installed the Websharper package on my ASP.NET MVC project and followed step 1 of the instructions, but I'm confused about the rest.

For step 2, where or how do I add the Websharper application that I want to integrate? Do I just add the F# source file in the scripts folder and have it automatically generate the Javascript that i need? Or do I have it compile in a separate Websharper project and add the generated Javascript into the ASP.NET MVC project?

In the title itself, it specifically says integration with ASPX pages. Does that mean this won't work with Razor web pages, which is the default for ASP.NET MVC?


Solution

  • Inserting WebSharper controls inside Razor pages is indeed not easy to do with the currently released WebSharper, but we are working on helpers to facilitate this, which will be released soon. The work in progress is available here. It relies on the latest WebSharper, so you need to build both from source if you want to use it right now.

    Here is what you then need to do (subject to slight changes before we release WebSharper.AspNetMvc):

    • Reference WebSharper, WebSharper.AspNetMvc and your WebSharper project from your web project.
    • If you use RPC and/or Sitelets:

      • Add the relevant module(s) to your Web.config as shown in the documentation you linked;
      • Add to your FilterConfig.RegisterGlobalFilters:

        filters.Add(new WebSharper.AspNetMvc.Filter());
        
    • To use client-side controls:

      • In your main razor layout, inside the head tag, add the following:

        @WebSharper.AspNetMvc.ScriptManager.Head()
        

        This will contain the css and javascript tags required by your controls.

      • To insert a control in a view, first create it at the top of the view:

        @{
            var myControl = WebSharper.AspNetMvc.ScriptManager.Register(new MyControl());
        }
        

        and then you can insert it in the view, eg:

        <div>
            <h1>My control:</h1>
            @myControl
        </div>
        

        It is important to create the control before the view starts rendering, or else ScriptManager.Head() will already have been rendered without this control's dependencies.