You are here:   Blog
Register   |  Login

 

Nov 1

Written by: Michael Washington
11/1/2013 3:20 PM  RssIcon

image

You can use ASP.NET MVC with Visual Studio LightSwitch.

This article would not be possible without the information provided by Dale Morrison (blog.ofanitguy.com):

Create The LightSwitch Project

image

Using Visual Studio 2013 (or higher), create a new LightSwitch application.

image

Right-click on the Server project and select Manage NuGet Packages

image

Install the following packages:

  • Microsoft.AspNet.Mvc
  • Microsoft.AspNet.Identity.Core

 

image

Right-click on the Server project and select Add Reference…

image

Add a reference to:

  • System.Web.ApplicationServices

 

image

Create the following folders in the Server project:

  • App_Start
  • Controllers
  • Models
  • Views

image

Add a class file to the App_Start folder called RouteConfig.cs and use the following code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LightSwitchApplication
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            // This rule is required to allow the LightSwitch OData service to
            // be accessed when WebAPI is also enabled
            routes.IgnoreRoute("{*allsvc}", new { allsvc = @".*\.svc(/.*)?" });
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { 
                    controller = "Home", 
                    action = "Index", 
                    id = UrlParameter.Optional }
            );
        }
    }
}

 

image

Add a Web.config file to the Views folder and use the following code:

 

<?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.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>
  <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=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, 
        System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, 
        System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=5.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>

 

image

Add a Global.asax file to the Server project and use the following code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace LightSwitchApplication
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

 

Create the MVC Controller

image

Add a class file to the Controllers folder called HomeController.cs and use the following code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace LightSwitchApplication.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
    }
}

 

Create the MVC View

image

Create a folder under the Views folder and call it Home.

Right-click on the Home folder and select Add then MVC 5 View page (Razor).

image

Give the View the name Index.

Use the following code:

 

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="HandheldFriendly" content="true" />
    <meta name="viewport" content="width=device-width,
          initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no" />
    <title>Welcome to MVC</title>
</head>
<body>
    <div>
        <h1>Hello from MVC!</h1>
        <a href="HTMLClient">LightSwitch Application</a>
    </div>
</body>
</html>

 

image

Run the application…

You will see an error that there is no home screen defined.

(you can eliminate this error by actually creating a LightSwitch screen)

image

However, if you navigate to the root of the application will see the MVC 5 application.

(this takes you to the Home controller that will then load the view for the Home controller)

 

More On LightSwitch and MVC

Allow LightSwitch Users To Self-Register and Change Passwords Using MVC

Creating an AngularJS CRUD Application Using Visual Studio LightSwitch

Using JayData to Consume the Visual Studio LightSwitch OData Business Layer in a AngularJs CRUD Application

 

Download Code

The LightSwitch project is available at http://lightswitchhelpwebsite.com/Downloads.aspx

(you must have Visual Studio 2013 (or higher) installed to run the code)

Tags: MVC
Categories:

4 comment(s) so far...


Gravatar

Re: Using MVC With Visual Studio LightSwitch

Hi Michael,
I'm trying to use your example; all went well until I've reached the end:
the last two sentences confuses me a bit: "However, if you navigate to the root of the application will see the MVC 5 application. (this takes you to the Home controller that will then load the view for the Home controller)"
I've got the error message (creating a screen eliminates that) but at this point I don't know where to look.
Can you advise me?
Regards, Ruud

By Ruud Jeursen on   11/8/2013 6:11 AM
Gravatar

Re: Using MVC With Visual Studio LightSwitch

@Ruud Jeursen - If you download and run the my sample you should be able to go to the root of the application (meaning you don't need the "/htmlClient" part) and see the MVC page. It also shows up if you add "/home" to the URL.

By Michael Washington on   11/8/2013 6:13 AM
Gravatar

Re: Using MVC With Visual Studio LightSwitch

Michael:

This is great. Thanks a lot.

Bruce

By Bruce DeMoose on   12/24/2013 3:09 PM
Gravatar

Re: Using MVC With Visual Studio LightSwitch

Hi I have commented how to add the Global.asax to MVC. Please review the "Allow LightSwitch Users To Self-Register and Change Passwords Using MVC" article with regard to this issue.

By Cliff Lo on   12/25/2013 7:02 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Security Code
CAPTCHA image
Enter the code shown above in the box below
Add Comment   Cancel 

Microsoft Visual Studio is a registered trademark of Microsoft Corporation / LightSwitch is a registered trademark of Microsoft Corporation