You are on page 1of 12

Home .NET Tutorials Articles Write For Us About Contact jQuery- ASP.

NET EBook
Login/Subscribe
Views: 63561 52 retweet retweet 30
Free Download - Using ASP.NET MVC & Sitefinity to Create Commercial Websites
Dynamic Menus in ASP.NET MVC 4 using EF Code First
and jQuery
Posted by: Sumit Maitra , on 5/24/2012, in Category ASP.NET MVC
Abstract: By default ASP.NET MVC Project Templates come with a Menu that is hardcoded for each
controller. However in a real-life scenario, more often than not, we need our Menus to be dynamic and loaded
and managed with certain amount of flexibility. In this article, we will see how to create a single level Dynamic
Menu using EF code first and jQuery in an MVC Application.
Click Here to Download our Free Digital Magazine for .NET Professionals
Default static ASP.NET MVC Project Templates are a good starting point, however projects with even
medium complexity need certain amount of flexibility. In this article, we will create a simple single
level menu system that will group child menu items and give the flexibility of setting the Label, Action
and Controller names at run-time.
This article uses the code from the Live Tile jQuery Plugin article that we wrote earlier on
www.devcurry.com
The Backend
We will use SQL Server to store and EF to manage the Menu definitions. Our schema is as follows.
The Menu class is our container or logical grouping for MenuItems.
MenuItems encapsulate the Item details:
Id - Identifier
Name Label used in Menu
ActionName Name of action to be invoked
ControllerName Name of controller in which the action resides
Url If Action Name is empty, one can provide a direct URL that the menu should point to.
ParentMenu A navigation property to the container Menu
B OOK S WR I T T EN B Y US
. NE T T OOL S
L I K E US ON F AC E B OOK
P OP UL AR ART I CL E S
Dynamic Menus in ASP.NET MVC 4 using EF
Code First and jQuery
Download Files in ASP.NET MVC 3 using
Controller Action
Understanding Routing in ASP.NET MVC
Consuming ASP.NET Web API in a Metro Style
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
1 of 12 11/6/2012 10:26 AM
We persist them in SQL Server using EF Code First.
Building the UI for Administration of the Menus
We start off with our LiveTile project that was built from an empty MVC4 project. It has only
got Index.cshtml under Home. We will build the Administration as well as the Menu on top of this.
Step 1: Copy the _Layout.cshtml and rename the new file as _LayoutAdmin.cshtml. Change the
header to LifeTile.js Admin
Step 2: We create a Controller using the standard MVC Scaffolder that we can bring up by Right
clicking on Controllers folder and selecting Add Controller.
- Click on Advanced Options and select _LayoutAdmin.cshtml as the master page. This is important
because we want the menu to be cached for regular pages that use the default master pages. On the
other hand the Admin page will be setup to not use any caching so that changes to the Menu are
reflected immediately.
Sony Lutfor J anaka Swetha
Ujjawal Priyatam
DotNetCurry on Facebook
5,861 people like DotNetCurry.
Like
Facebook social plugin
Follow
Application using jQuery
RavenHQ and ASP.NET MVC Moving your
Data to the Cloud using AppHarbor
Display Charts in SharePoint 2010 using Excel
Services and Chart Web Parts
The Magic of Visual Studio 2012 Page
Inspector
Silverlight 5: Some New Features For
Developers
Simple .NET Database Programming using SQL
Azure
Managing Structured Data using Windows
Azure Table Service
Creating a Data- Bound application using
Infragistics xamGrid Control
Creating a HTML5 Chart Helper Extension for
ASP.NET MVC 4
Server Side Timer in an ASP.NET MVC
application using SignalR
Hosting WCF Service on Windows Azure
Using TFS 2012 and SCRUM for Iteration
Capacity Planning for Software Development
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
2 of 12 11/6/2012 10:26 AM
- Finish the Controller creation by click the Add button. This will scaffold all the methods and views
required for Menu creation. Now we repeat the same for MenuItem and create a new controller
MenuItemController using the same Data Context and the Admin specific master page.
Step 3: Next we update the connection string in the web.config by changing the Name to LiveTileDB
and the connectionString to point to the correct catalog.
Step 4: Then we update the DBContext such that it uses the correct connection string. As seen
below, we pass it to the base in the Constructor.
We have also overridden OnModelCreating and passed it the Initializer CreateDatabaseIfNotExists.
This ensures EF simply creates the DB if it does not exist.
Step 5: MenuItems dont really exist on their own, they HAVE to be a part of some Menu. So lets
delete the MenuItem\Index.cshtml.
Step 6: MenuItems instead will be shown in the Details page of the Menu. So we update the
Menu\Details.cshtml as follows
E- mail
Name
Yes, I want to Subscribe!
F RE E MAGAZ I NE S UB S CR I P T I ON
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
3 of 12 11/6/2012 10:26 AM
We are adding the rendering details for MenuItems in the Menu\Details page itself. Not only that, for
each MenuItem, we are setting up the Edit and Delete action link that will enable us to Edit and
Delete the MenuItems from the Details page itself. At the bottom we have also added the Create
MenuItem Action link.
Step 6: Update the MenuItem Controller. In the above step, we have seen that all the action links
pass additional parameters for the HTTP GET operation. This is to let the controller know which Menu
the Menu Item is associated to. To accommodate this, we update the MenuItemController as follows
Creation Action
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
4 of 12 11/6/2012 10:26 AM
Edit Action
Delete Action
With the Details View and Controller setup like this, we are ready to create Menus and MenuItems.
Run the Application and navigate to /Menu to get the following:
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
5 of 12 11/6/2012 10:26 AM
Click on Create New and add a new Menu called Main.
Click on the Details to get to the Details page.
Click on Add Menu Item and add a MenuItem with Name = Home, Action=Index, Controller=Home.
Add another with Name = About, Action = About, Controller=Home. The Details page will now look as
follows
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
6 of 12 11/6/2012 10:26 AM
So now our backend is all set with a Menu and a few MenuItems. Time to get the rendering work in
place!

Rendering the Menu
Step 1: Add a Partial View called _MenuLayout.cshtml under the Views/Shared folder. Make it
Strongly Typed of type Menu.
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
7 of 12 11/6/2012 10:26 AM
Step 2: Update the View as follows
Thus the Menu is nothing but a List with each menu item being a list item.
Step 3: Update the HomeController.cs with the following action method
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
8 of 12 11/6/2012 10:26 AM
This will be called to generate the PartialView of the Menu. Here we have hardcoded the Menu name
(Main). The method returns just the HTML for the _MenuLayout.cshtml file with the given Model
(menu).
Step 4: Update the _Layout.cs
Add a <nav> section with an empty div with id navcontainer. We will replace the contents of this div
with the partial view.
Add the following JavaScript at the bottom of the _Layout.cs
This script is nothing but a jQuery postback, it is fired once the document is loaded. And on a
successful return ,it simply dumps the response HTML into the container.
Step 5: Update _LayoutAdmin.cs with the same except for one change in the JavaScript. We disable
caching for the Admin pages.
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
9 of 12 11/6/2012 10:26 AM
52 retweet retweet
Step 6: Prettify it by updating the CSS for converting the <li> elements into a Tab layout.
Thats it, we are done. Run the Application to see the Menu getting rendered.
Navigate to the Admin page at /Menu, make some changes to the Name of the MenuItems and see
them getting reflected immediately. Clicking on the Home link will navigate back to Home page.
Clicking on About will throw an error because we dont have an About page yet.
Conclusion
With that, we conclude this post. We saw how to create the backend and related admin screens for a
simple Menu system for an ASP.NET MVC 4 application. We also saw how MVC partial views are used,
how to deal with Master-Child UI by passing the Masters Id around and last but not least, how jQuery
can be used to do partial postback.
The entire source code of this article can be downloaded over here
See a Live Demo
Gi ve me a +1 i f you thi nk i t was a good arti cl e. Thanks!
30
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
10 of 12 11/6/2012 10:26 AM
Server Side Timer in an ASP.NET MVC application
using SignalR
Creating a HTML5 Chart Helper Extension for
ASP.NET MVC 4
Understanding Routing in ASP.NET MVC
RavenHQ and ASP.NET MVC Moving your Data to
the Cloud using AppHarbor
Download Files in ASP.NET MVC 3 using Controller
Action
Using RavenDB and ASP.NET MVC 4 to create a
Twitter Clone Chirpy
Sumit is a .NET consultant and
has been working on Microsoft
Technologies for the past ten
years. He loves developing using
C# on the .Net platform but not
opinated against any programming language!! Hes
currently working on custom SharePoint
applications and ASP.NET MVC and hopes to master
development for the Mobile platform someday
soon.You can reach him at
sumitkm[at]gmail[dot]com or tweet him at
@sumitkm
RECOMMENDED ARTICLES
USER FEEDBACK
Comment posted by a on Monday, June 04, 2012 8:30 AM
hello , very intersting however the"Live Demo" has a "Internal Server Error"....
Comment posted by Sumit on Wednesday, June 06, 2012 4:37 AM
Hello a,
Yup, since it's open to modifications, if you change the Menu name from the default "Menu" it goes off the rockers.
Simple fix to test it out is to have atleast One top level Menu's Name set as 'Main' :). I just fixed it back.
:)
Comment posted by Sergei on Tuesday, July 03, 2012 7:36 PM
Live Demo: Internal Server Error:)
Comment posted by Prakash Kumar on Thursday, July 05, 2012 12:39 AM
Nice concept :)
Comment posted by Sumit on Thursday, July 05, 2012 2:37 AM
Thanks Sergei,
Thinking of Blocking users from making changes to 'Main' Menu :-). Or adding a admin page to allow them to
select their top level Menus :-).
Thanks Prakash.
-Sumit.
Comment posted by Sumit on Thursday, July 05, 2012 5:03 AM
We have had to disable Add/Edit/Update/Deletes on the Demo site because of XSS attacks.
We get it the current code does not use Anti-XSS best practices, if we were to include all best practices of web
development in every demo we did, the essence of the article would get lost.
Asp.net Jobs
Exp1-4 yrs, Sal Upto 6 Lac/Annum Upload Your CV To Apply Now.
careerbuilder.co.in/ASP_Dot_Net
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
11 of 12 11/6/2012 10:26 AM
It's a demo, let it remain one.
Comment posted by lol indus code on Tuesday, July 10, 2012 5:41 PM
omg my eyes, this is real indus code
Comment posted by Lucas on Wednesday, August 08, 2012 3:12 AM
Code and idea is really great!
But I have a problem.
How to store extra attributes in menu item like id or name. For example www.mysupersite.com/user/edit?id=3
where controller is user, action is edit and extra attribute (parameter) is id
Comment posted by Sumit on Sunday, August 12, 2012 3:42 PM
Hello Lucas,
You can add, additional attributes in the MenuItem for saving. To get those information in the menu like, look at
Step 2. We are creating the Menu links using the Html.ActionLink(...). There is an overload to specify an
anonymous object with name/value pairs that will be passed as query string. Use that overload to pass the
additional information.
Hope this helps,
Sumit.
Comment posted by filz on Saturday, August 18, 2012 6:26 AM
very nice
http://www.woll-filz.com
POST YOUR COMMENT
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel
ASP.NET
ASP.NET MVC
jQuery ASP.NET
SharePoint
VisualStudio & TFS
POPULAR CATEGORIES
Write For Us
About
Contact
Advertise
Privacy Policy
LINKS
Join Us On FaceBook
Subscribe to RSS
Follow on Twitter
SOCIAL NETWORK
Copyright 2012 dotnetcurry.com (Best Viewed at 1024 * 768 or above)
Covering ASP.NET, MVC, Win 8 Apps, Azure, SharePoint and more..
Dynamic Menus in ASP.NET MVC 4 using EF Code First and jQuery http://www.dotnetcurry.com/ShowArticle.aspx?ID=811
12 of 12 11/6/2012 10:26 AM

You might also like