Back to blog

Sitecore MVC Music Store

May 17, 2012 - Posted in asp.net mvc , c# , sitecore Posted by:

In my last blog post about using the MVC Framework inside Sitecore, I announced that I’d write another blog post on how to actually create a real world application with MVC inside Sitecore. The first blog post was just a proof of concept, creating a real world application with it, helps completing the code.

In the meantime, Sitecore has announced that it will support MVC in Sitecore version 6.5.1. Great news! I got a sneak preview of what they’ve made, looks great. From what I’ve seen, this tutorial won’t have to change much when they’ve released the official version. I’ll update the tutorial as soon as 6.5.1 will be released.

Since Microsoft has already created a nice tutorial for getting started with ASP.NET MVC : MVC Music Store tutorial. I figured it’d also be a nice tutorial to get started with MVC inside Sitecore. It’s an easy to follow, small tutorial, which makes it easy to go through for both experts and beginners in the world of MVC. Experts can just skip the parts explaining how MVC itself works and go straight to the action. For beginners, the entire tutorial takes less then 2 hours. It’ll be the best invested 2 hours of your programmer’s life so far :)!

Once you have completed the Microsoft tutorial, the steps in this blog-post will help you transform it to a Sitecore project.

Step 1 – complete the tutorial

First, follow the entire tutorial (or if you’re an expert on MVC already, just download the package:http://mvcmusicstore.codeplex.com/)

Step 2 – copy contents

Copy the wwwroot contents of the mvcmusicstore project into the wwwroot of an existing Sitecore project (or create a new one first), but SKIP the web.config files! Note that you should copy the web-files to the web folder of your sitecore project! (if you downloaded the package, the web-content is inside the ‘MvcMusicStore’ folder inside the zip file)

Now open the Sitecore project in visual studio, and add the project you just copied to your solution (File –> Add –> Existing project).

Step 3 – nuget package

Install the NuGet package BoC.Sitecore.Mvc (not the starter app) to your just added project. You can do that either through the package manager console or through tools->library package manager->Manage NuGet Packages for Solution…

This will modify your web.config to allow MVC applications inside your sitecore website, and will add the BoC.Sitecore.MVC reference which holds all the MVC magic.

Step 4 – connectionstrings

Now, copy the connectionstring in the web.config of the original created MVCMusicStore project, to the App_Config\Connectionstrings.config inside your sitecore solution.

If you now run your application, and everything went fine, your application should work exactly the same as when you finished the tutorial. (Note: if you downloaded the sample code instead of making your own, and you run in to the error code  “Unable to find the requested .Net Framework Data Provider.  It may not be installed.”, you need to install MS Sql Compact CE 4.0)

These first 4 steps were the steps required to get an existing MVC application working inside the sitecore wwwroot. Now we’ll start modifying the existing app to become an application fully powered by sitecore!

Step 5 – Global.asax

Running the application worked just fine, but there’s no sitecore magic somewhere in the pipeline, so let’s add that. First, we’ll modify the default route in global.asax.cs. You can do that by adding any static string value in front of the default route. I chose ‘musicstore_api’. Doing this will make all your controller actions accessible through /musicstore_api/home/index, this could come in handy for stuff you need to access without going through sitecore (eg. ajax calls, delete actions, etc)

image

Step 6 – Create ‘GetLayout’ controller action and view

Using BoC.Sitecore.Mvc, if you want a Razor view as your layout, you’ll have to load it through a controller action. If you don’t like creating a controller action for just loading the base layout, you could use Robert Jongkind’s RazorForSitecore module, it will all mix and match just fine. Sitecore 6.5.1’s version of MVC will also support picking a Razor view without a controller as your layout..

For now however, we’ll stick to using just the SitecoreMVC way. Open your HomeController.cs file and add new action called ‘DefaultLayout’. The only thing that action should do, is return View():

image

Also create the accompanying view, with just 1 line telling Sitecore it can render a placeholder with key “main” in this view. (Html.SitecorePlaceholder is an extension method inside BoC.Sitecore.MVC)

image

Step 7 – Create Sitecore templates

Run your application, and go the the Sitecore desktop (/sitecore/shell/default.aspx) and open the template manager.

Screenshot - 3-6-2012 , 14_14_50 

Add a new template folder underneath ‘Templates\User defined’ called ‘MVC MusicStore. Underneath that new folder, add a new template.

image

Call the new template ‘Default page’ and just let the base template field as it is. Click next, next, finish.

image

Select your new ‘Default page’ item in the tree, and on the ribbon ‘Builder options’ click the ‘Standard values’ button in the template section.

image

And next on the ‘Presentation’ ribbon, click the ‘Details’ button in the layout section

image

This will open the layout details wizard:

image

Here, click the Edit-button under the ‘Default’ section (marked with a red border in the screenshot above), which will open the “Device Editor” popup:

image

In the dropdown, choose the ‘DefaultLayout’ MVC action underneath the Home controller and click OK twice

image

Step 8 – Create sitecore items

Based on our just created ‘Default page’ template, we’re now going to add the Sitecore items based on this template.

Open up the content editor in sitecore, and delete the exiting homepage item (/sitecore/content/home). Add a new Home item by click the ‘Content’ item with the right mouse button and choosing ‘Insert –> Insert from Template’.

image

Call the item Home and pick our just created ‘Default page’ template as it’s template

image

Using this same template, create the following tree inside Sitecore:

image

Notice the * in front of Genre and Id…. these are wildcard mappings! The name of the items should be * and the displayname *Genre and *Id.

Step 9 – Attach controller actions

On these pages, we’ll attach the appropiate MVC Action. Start with the Home item. Click on it in the tree, and open the ‘Presentation’ ribbon. Now click on the details button:

 image
This will open the layout popup

image

Now click the Edit-button under the ‘Default’ section (marked with a red border in the screenshot above), which will open the “Device Editor” popup image

Click the controls tab, and choose ‘Add’. That will bring up the ‘Select a rendering’ window.

image

Choose MVC Actions/Home/Index and enter ‘main’ as the placeholder name (remember we added that $Html.SitecorePlaceholder(“main”) to DefaultLayout.cshtml?). Click on Select, and then on OK twice to save all your changes.

Now do the same for all other pages you’ve created except the ‘checkout’ page (that is just a placeholder). The other pages should get the following controls:

  • Checkout –> MVC Actions/Checkout/Complete
  • Checkout/AddressAndPayment –> MVC Actions/Checkout/AddressAndPayment
  • ShoppingCart –> MVC Actions/ShoppingCart/Index
  • Store –> MVC Actions/Store/Index
  • Store/Browse –> MVC Actions/Store/Browse
  • Store/Browse/*Genre –> MVC Actions/Store/Browse
  • Store/Details –> MVC Actions/Store/Details
  • Store/Details/*Id –> MVC Actions/Store/Details

Step 10 – Publish & test

Now, publish your entire site (! beware that if you’re using the sample database with the sample item template, that there is a worfklow attached to the new items by default… you need to approve them before publishing). After publishing, you can go checkout the homepage of your website.

Hey! the navigation menu and logo are shown twice!

image

Step 11 – Modify viewstart

The reason for the page being displayed twice, is because the default MVC Musicstore project does not take into account that the views can be accessed as a child-action. Adding the actions as a sublayout inside our sitecore pages, makes the actions being rendered as childactions. To skip the layout being rendered in child mode, open Views/_ViewStart.cshtml and modify the one line that’s in there to:

image

Save the file, and check the homepage again: Looking much better!

Step 12 – Modify Links

Though the app looks good now, all links are pointing to the /musicstore_api folder. Even though that will work just fine, that’s the native MVC you’re calling then. To point all links to the sitecore versions, we’ll have to change all link renderings. This is the most dramatic change in an existing MVC app. In fact, we’ll break compatibility here, since the links will become Sitecore specific. I haven’t figured out a way to keep this compatible. Then again, I don’t think you’d ever even want that. Thing is, with a standard MVC application, a controller action always has it’s own url. With SitecoreMvc any page in Sitecore can use the same MVC Action over and over again, on different url’s. This is so different, it’ll be impossible to keep things cross-compatible.

Open Views/Store/GenreMenu.cshtml. Modify the @Html.ActionLink in there, to the following:

image

See how we’ve mapped Genre as a parameter? The wildcard resolver will pick that up. We could have also placed the name in the path attribute, that would resolve just the same:

image

Now do the same for all other links in the project. In Views/Home/Index.cshtml and Views/Store/Browse.cshtml change the action Url.Action to
image

The Html.ActionLink in Views/Store/Index.cshtml to
image

The Html.ActionLink in Views/ShoppingCart/CartSummary.cshtml to
image

In Views/ShoppingCart/Index.cshtml, change the $.post(“/ShoppingCart/RemoveFromCart” to
image
(See how this will go directly to MVC! This won’t hit any Sitecore item, hence the url would become /musicstore_api/shoppingcart/removefromcart).

In the same file, replace the checkout Html.ActionLink with
image
and the details Html.ActionLink to
image

In Views/ShoppingCart/Complete.cshtml change the Html.ActionLink to
image

In Controllers/ShoppingCartController.cs, in the AddToCart method, change the RedirectToAction to
image

and, the last one, in Controllers/CheckoutController.cs, in the AddressAndPayment method, change the RedirectToAction to
image

Step 13 – Remove authorization

As a last step remove the Authorize attribute on the CheckoutController. In this tutorial, we’ll not be setting up Account related stuff, it’ll be taken care with in the follow-up of this post.

image

Step 14 – Run

Now run your project again! Everything but Account-related stuff should work fine now! Add albums to your cart, check out, etc.

Conclusion

That concludes this tutorial for now. It should give you a good idea on how to get MVC up and running for your Sitecore projects.In the next blog post about Sitecore & MVC, I will explain how to use the Sitecore security in this MVC Musicstore and we’ll get rid of the external database by creating Sitecore items for the albums. The albums will the be editable using both the Sitecore content-editor AND page-editor. So watch this blog for the follow-up, though I’ll first write a post on an other topic.

3 Comments

Richard Dias 2 years ago

Thanks for the article Chris, I had a feeling that Sitecore 6.6 (yes its no longer called 6.5.1) will be very similar to your initial implementation of MVC for SC.
Keep it coming!

Alan Gallauresi 2 years ago

Thank you for all the work on this MVC implementation in Sitecore, Chris – it is really impressive. Have you had a chance to compare it to Sitecore 6.6′s methods in depth yet? I am particularly struggling with trying to implement controller renderings in 6.6 to emulate your method of including controller actions as sublayouts. Also I have yet to see the full controller/action set as a data provider like you setup, and I’m not sure whether that is a part of the 6.6 implementation or it’s expected the dev would add a provider if required.

Thanks! Alan

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>