Hands on with ASP.Net MVC

Hands on With ASP.NET MVC
Rahul Sahay
Quills Ink Publishing
Copyright © 2014 Rahul Sahay
Hardcover ISBN : 978-93-84318-52-9
Softcover ISBN : 978-93-84318-53-6
Ebook ISBN : 978-93-84318-54-3
Design and Setting By
Quills Ink Publishing

All rights reserved. No part of this publication may be reproduced, distributed, or transmitted in
any form or by means, including photocopying, recording, or other electronic or mechanical
methods, without the prior written permission of the publisher.
The views and characters expressed in the book are of the author and his/her imagination and do
not represent the views of the Publisher.

Chapter 1: Getting Started
WHAT DO you find in this CHAPTER? 1
Introduction 2
Understanding ASP.NET MVC 2
The MVC Pattern 3
Brief History of MVC Pattern 4
MVC Life Cycle 6
Software Requirements 7
Application Glimpse 8
Creating a MVC application 19
How MVC applications are structured 22
Summary 24

Chapter 2: Understanding Controllers
WHAT DO you find in this CHAPTER? 25
Introduction 26
Controllers 26
Working with your 1st controller 30
Action Results 39
Action Selectors 45
Action Filters 49
Summary 49

Chapter 3: Views
WHAT DO you find in this CHAPTER? 50
Introduction 51
Views 51
Syntax of Razor Views 59
How to Prevent Cross Site Scripting Attack 60
More on Razor Syntax 62
Layout Views 68
HTML Helpers 77
HTML.ValidationSummary 86
Some more HTML Helpers 87
Partial Views 91
Viewbag and Viewdata 94
Summary 95

Chapter 4: Getting Started with Data modeling
WHAT DO you find in this CHAPTER? 96
Introduction 97
Using Entity Framework 97
Entities Creation 98
Database Migrations 107
LINQ 114
Search Query 118
Summary 122

Chapter 5: Data modeling- Part 2
WHAT DO you find in this CHAPTER? 123
Introduction 124
Organizing Movie Controller 124
Reviews Listing 137
Create and Edit Facility of Review 142
Validation Annotations 154
Summary 157

Chapter 6: JavaScript and AJAX in MVC
WHAT DO you find in this CHAPTER 158
Introduction 159
Managing Scripts 159
Ajax Helpers 165
Async Search 174
Paging 179
Summary 188

Chapter 7: Security with ASP.Net MVC
WHAT DO you find in this CHAPTER? 189
Introduction 190
Authentication 190
Membership and Forms Authentication 196
Authorize 212
Seeding Membership 216
Cross Site Vulnerability 223
OpenID and OAuth 226
Summary 230

Chapter 8: Caching – ASP.Net Terminology
WHAT DO you find in this CHAPTER? 231
Introduction 232
Caching 232
Cache Profiles 235
Localization 237
Resource Files 241
Diagnostics 247
Summary 256

Chapter 9: Unit Testing
WHAT DO you find in this CHAPTER? 257
Introduction 258
TDD 258
Home Controller Tests 268
Web Tests 276
Load Tests 281
Code Coverage 290
Summary 292

Chapter 10: Deployment
WHAT DO you find in this CHAPTER? 293
Introduction 294
Configuration Files 294
Hosting ASP.Net MVC Application 298
Deployment Preparation 301
Deployment on IIS 309
Deployment to Azure 324
Summary 333

Chapter 11: Routing Basics
WHAT DO you find in this CHAPTER? 334
Introduction 335
Route Definition 335
Areas 337
Ignore Routes 338
Debugging Routes 338
Constructing URLs from Route 340
Route Data 341
Route Constraints 342
Summary 342

Chapter 12: Web API and Dependency Injection
WHAT DO you find in this CHAPTER? 343
Introduction 344
Why Web API 344
Creating a new empty Project 345
Adding Web API to an ASP.Net Project 351
Creating your 1st controller 353
Dependency Injection 356
Implementing POST 363
Implementing DELETE 367
Implementing PUT 370
Summary 372

Chapter 13: Making a Mobile Site Using Jquery Mobile
WHAT DO you find in this CHAPTER? 373
Introduction 374
Setup 374
Viewports, Widgets and Attributes 377
Themes and Swatches 386
Media Query 387
Layouts and Pages 389
Collapsibles 400
Grids and Buttons 406
Forms 410
Summary 411

Chapter 14: ASP.NET MVC 5
WHAT DO you find in this CHAPTER? 412
Introduction 413
Scaffolding 413
ASP.Net Identity 421
One ASP.Net 421
Bootstrap 427
Attribute Routing 432
Filter Overrides 435
Summary 438

Chapter 15: ASP.NET MVC 6
WHAT DO you find in this CHAPTER 439
Introduction 440
Features 440
Prerequisites 442
Setting up VM 442
Getting Started with Visual Studio 14 447
Creating your 1st Visual Studio 14 MVC Project 449
Configurations in MVC Project 451
project.json 452
Startup class 459
Adding a Class Library Project 462
Deployment to Azure 468
Bin 476
Self Hosting 477
Summary 483

Index 485

Hands-on with ASP.NET MVC book give you a fine Launchpad to get started on MVC. I have written the book in such a fashion that you will solve one case study while studying the book. By the time you will finish the book, you would have completed web version and mobile version of development using MVC. Now, one important point to understand here that ASP.NET MVC is a major shift for all Microsoft developers. ASP.NET MVC emphasizes clean architecture, design patterns and testability. At every part of the book you will get practical example of all the theoretical concepts with complete demo.

ASP.NET MVC is basically a web development framework from Microsoft which combines the features of MVC (Model-View-Controller) architecture. Now, ASP.NET MVC is not something which is built from the ground zero. It built on the top of ASP.NET, so developers enjoy almost all the ASP.NET features while building the MVC application. ASP.NET MVC is an alternative approach to an existing Web Forms approach. This book is basically comprised of 15 chapters covering all the parts of MVC development. 1st chapter starts with the introduction of ASP.NET MVC where in you will see how MVC gained maturity in different releases. 1st chapter will also showcase that what you are going to build by giving the application glimpse in its finished form. Then, you will start creating your MVC project right from the scratch.

In 2nd Chapter you will get the complete idea of controllers. Here, after understanding the basics of controllers, you will be writing your 1st controller. 2nd chapter also covers different types of action results, filters and many more things. 3rd chapter will have view introduction with syntactic sugar. This section also explains some of the core concepts of data – (dash) attributes that how views behind the scenes emit these tags. Apart from HTML helpers, you will also work with different types of view in it. Chapter 4 and 5 will be all about data modeling. In this chapter you will come to know how to get started with entity framework, also how to setup the entities and migrations. Here you will also see different types of validations in action.

Chapter 6 is all about Client side scripts. Its main focus would be on how to manage scripts, how to work with Ajax helpers and how to write an Async Search. Chapter 7 is covering all the security related features like Membership, Authentication, Roles, Open Authentication and many more things. Now, chapter 8 is all about infrastructure topic like Caching and different Diagnostics techniques. This topic stresses how to improve the Application performance by implementing caching. 9th chapter is all about testing. It start with unit testing where in you can test your application logic, then web testing and load testing where in you can test your website performance in different test scenarios. Then we have 10th chapter which is all about deployment. In this case you will 1st deploy the application to IIS, then on internet on AZURE.

Chapter 11 is all about routing concepts. This chapter deals with different routing rules. Then, chapter 12
comprise of Web API and Dependency Injection. Both of these topics are really important and interesting as well. You will learn how to implement both with a complete application demo. In chapter 13, you will be optimizing your application in such a way that it will support mobile browsers as well. Then, Chapter 14 is dedicated to the new features of ASP.NET MVC 5 with complete demo. Last but not the least which is the bonus part of this book MVC 6; here, in chapter 15 you will start from the features discussion, then prerequisites required for MVC 6. MVC 6 is a major breakthrough from Microsoft side towards being Open Source Compliant. So, stay tuned for a stunning journey.

This book would not have been possible without the patient and loving support of my wife Nivi, who had to take over much of the household responsibility apart from her teaching activities, so I could whisper to myself in the corner and do my activities with my laptop. Many thanks also go to my publisher, Rohan Vij, who took this responsibility, to publish the book in a precise and correct way. Appreciation also goes out to my Mom and Dad for believing in me and always keeps on encouraging me to complete the book in a best possible way. Also, I need to acknowledge you, the reader, for your desire to continue your own growth not only as developer but a smart
developer. Obviously, your efforts to improve your skills make me all work to improve myself to keep up the good work. Kudos to you, and keep setting the pace at your workplace!

I would also like to Thank Sanjay for writing the FOREWORD for me. He took his time from his day to day busy schedule, read the complete book; gave his suggestions for improvement and finally after implementing his suggestions he wrote foreword for me.


Hand-on with ASP.Net MVC is designed to teach ASP.NET MVC, from grass root level to advanced topics. I have written the book in such a way that even if you are new to ASP.Net background, you won’t feel difficulty in understanding the concepts. I also understand that many of our readers are familiar with ASP.NET Web Forms, so one important point to understand here that ASP.Net MVC is not a replacement to Web Forms at all. Now, onwards there will be one more design technique to build websites. I have worked hard to make sure that this book is valuable for developers who are experienced with ASP.NET MVC, or even freshers coming out of college. This book is also very well suited to 3rd year and Final year student as this will help them greatly while building their projects.

Also, since ASP.NET MVC is one of the hottest trends across industry, so from the point of interview
preparation as well, it will be a good reference book. Now, apart from MVC you will also learn how to convert the same app to support mobile browsers, also how to host the app on Azure (Microsoft’s Cloud Version).

Today I am really thrilled to introduce this book covering the latest release of ASP.NET MVC, written by one my friend Rahul Sahay. Rahul was developer when I interacted with him for the first time. He is tech extrovert and
interacting with wide variety of technology to gain knowledge, guideline and feedback. His interactions with the diverse ASP.NET community give him some great insights on how developers can begin, learn, and master ASP.NET MVC. He is helping number of blog followers on various topics which is known to him and generated a lot of fans and followers with his technical skills. With a background rooted in community and open source, I count him not only as an amazing technologist but also a close friend. There are number of frameworks available in market but ASP.NET MVC 6 brings you a new ASP.NET Web API (a new framework for building HTTP services), updated default project templates that leverage modern web standards, solid mobile web application support, enhanced support for asynchronous methods, and more with easy integration with other microsoft technology. Currently, MVC 6 is in beta version, which will be officially releasing next year. But, Rahul took this opportunity to include MVC 6 as well in this book. Before touching MVC 6, he has also covered MVC 5 and 4 with complete detail with live demo.
Rahul also developed number of tutorials to help developer understand concepts and also planning to upload a number of videos in line with it. One can always refer his articles on his blog (http://myview.rahulnivi.net/).

Sanjay Kumar Sinha
BTech- IIT
Solution Architect


Finally, this book is mostly based on my opinions. I made every possible effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. I’ve spent a lot of time researching the topics in this book and I implement from real world experience as much as possible. With that words, if you find something you believe is absolutely wrong—or even something you strongly disagree with—let me know @:rahulsahay19@gmail.com.

Chapter 1: Getting Started

WHAT DO you find in this CHAPTER?

Understanding ASP.NET MVC
The MVC Pattern
Brief History of MVC Pattern
MVC Life Cycle
Software Requirements
Application Glimpse
Creating a MVC application
How MVC applications are structured

Hi Friends, My name is Rahul Sahay, your instructor for ASP.NET MVC. In this section I’ll walk you through the overview of MVC. I’ll also give a brief snapshot of the History of MVC when it’s first introduced and then start the development process. I assume that most of the readers who are reading this book are from the ASP.NET background. However, even readers who are new to ASP.NET architecture don’t need to bother at all as I start right from the grass root level. So, let’s get started.

Understanding ASP.Net MVC:-
ASP.NET MVC framework basically designed to build the web applications which take the general legacy approach Model View Controller Pattern. This pattern existed in tech space since decades; this is not something which is being built by Microsoft from ground Zero. However, Microsoft has introduced its very own MVC framework called as ASP.NET MVC Framework. Also, it’s equally important to understand that Microsoft hasn’t written this MVC Framework right from the scratch, rather it’s been built on the TOP of ASP.NET which means, ASP.NET MVC still has almost all features of ASP.NET like Master Pages, Session Management, Caching, Different types of Authentication and many more thing.

Also, one more important thing to understand here that ASP.NET MVC is not the replacement of ASP.NET Web Forms. Microsoft has provided MVC as an alternative approach to build the web application. So, going forward, now there will be two different approaches to build the web application. However, ASP.NET MVC basically follows the same core principle what other languages follow, plus it has got ASP.NET advantage, like it has got the support of Managed Execution Environment, it uses .Net feature like Extension Methods, DLR features and many more. Some of the common features of MVC which I would like to list out are:-

Stateless: – MVC Framework follows the stateless pattern which means there will be no illusion of state at all. Also, there will be no Page Life Cycle, no Server Side Controls and no View State also. So, instead of using any server side controls like Grid Controls or Menu Controls, we will be writing and crafting the HTML completely from scratch. So, this way we’ll be having complete control on our HTML.

No Page Extensions: – This is also one of the best things which MVC says, so there will be no page extension like .aspx. So, here URL comes is pretty handy and easy to use and easy to remember for readers and also for the search engines. Basically, it is said that pages which are coming without any page extension are ranked higher in the search engine.

Extensible: – This is also one of the common goals for MVC to be completely extensible throughout all the aspects. So, like when we talk about views, one may use aspx view engine to write the view or use the razor to do the same or user can download any other view engine and use the same with the project as well. But, in this case we’ll stick to Razor view engine.
Testability: – Testability is the one of the most important factor of using MVC. It’s basically quite simple, it maintains complete separation of concerns, and hence it’s easy to write and test for each module explicitly. So, here we can easily write test cases for each module explicitly.

The MVC Pattern:-


Having said to my earlier statement that ASP.NET MVC design pattern is not new, this is the technique which is being used since decades across many different technologies like C++, Java, etc. and now in C# as a design pattern for building web applications. It’s powerful and stylish design pattern mean for separation of concerns which means within the application itself we’ll be having separate Data Logic and UI Logic. Neither of these are dependent on each other. Hence, each of these can be tested separately by writing unit test cases. Below is the brief snapshot of MVC and its responsibilities.

Model: – Models are basically a collection of classes where in you will be working with data logic as well as business logic. So, basically models are containers which are business domain specific or I would say section which is used to interact with database and also used to manipulate the data to implement the business logic. So, with ASP.NET MVC this is pretty much easy to use data access layer with Entity Framework, ADO.Net or NHibernate combined with custom code.

View: – Views are nothing but a pure HTML which decides how the UI (User Interface) is going to look like. All I can say is that views are basically templates which decide the look and feel or presentation of your app. This is the section which is going to present the static HTML with extracted data from database @ the desired place.
Controller: – Controllers are basically a bunch of classes which handles communication from the user. This is the one which is responsible for taking incoming HTTP Request and transferring the control to the appropriate section of the application. So, this is the special class which wires up the relationship between view and model. So, it responds to the user input, interacts with the model and decides which view to render. Basically, Controller classes maintain one convention that it has to be suffixed with the name “controller”.
Brief History of MVC Pattern:-
ASP.NET MVC Pattern is the idea which is being developed by Scott Guthrie in 2007. He is the key architect of this design pattern. As far as my knowledge goes, I always designate Scott Gu, as the father of .NET. He is the main person who originated the idea of .NET. Since, then Microsoft or Scott’s team has added tons of feature in .NET development, which makes developer feel comfortable writing any kind of project using .NET.

ASP.NET MVC 1 Features:-
Here, in this section apart from separation of concerns, Unit tests were added. So, while writing any project, you could write unit test for specific modules side by side. MVC 1st was released on 13th March 2009.

ASP.NET MVC 2 Features:-
ASP.NET MVC 2 was released just in a span of 1 year. This has got some really cool features which make MVC more robust and powerful. This version was released on March 2010. Some of the features of MVC 2 have been listed below:-

• UI Helpers with Scaffolding templates.
• Model validation on Client and Server side.
• Strongly typed HTML Helpers.
• Enhanced Visual Studio tooling.

ASP.NET MVC 3 Features:-
ASP.NET MVC 3 was officially released in 2011. MVC 3 has come with major improvements in many sections. Some of the MVC 3 features are listed below:-

• Inclusion of Razor View engine.
• .Net 4 Data annotations.
• Robust model binding and validation.
• Inclusion of Global Action Filters.
• Nice JS, JQuery support. Also, included Unobtrusive JavaScript validation.
• JSON Binding
• NuGet Integration to resolve the software dependencies on the fly.

Don’t worry I’ll do detailing each of the topic in coming chapters; here I just want to make things clean and simple.

ASP.NET MVC 4 Features:-
ASP.NET MVC 4 has done value addition on MVC 3. On the other hand it has become a complete web development package as a whole which offers developer complete suites of development stack. Some of the common features are listed below:-

• Improved Project Templates. Added new Ones
• Inclusion of Mobile Projects using JQuery Mobile.
• Various Display Modes
• Asynchronous Controllers
• Bundling and Minification

ASP.NET MVC 5 Features:-
Again ASP.NET MVC 5 has done many value additions to MVC 4. But, all of these changes are around its scaffolding templates, authentication technique, Bootstrap and many more. Some of the common features are listed below.

• Scaffolding
• ASP.Net Identity
• One ASP.Net
• Bootstrap
• Attribute Routing
• Filter Overrides

You will learn complete features with demo in chapter 14.

ASP.NET MVC 6 Features:-
ASP.NET MVC 6 in many terms is a unique framework as it’s a major change in MVC. All these features will be discussed in the last chapter in detail, where we’ll see the glimpse of MVC 6. Below, I have listed some of the common features of MVC 6.

• Common Framework for MVC, Web API and Web Pages
• Smooth Transiting from Web Pages to MVC
• Built DI First
• Runs on IIS or Self Host
• Based on the new Request Pipeline in ASP.NET vNext
• Runs Cloud Optimized
• No Build Dependency
• Enhanced developer experience
• Open Source
• Cross-Platform Support

Apart from above listed features there are other things also involved which are explained with complete demo in Chapter 15.

MVC Life Cycle:-
MVC Life Cycle in a nutshell will give you glimpse of overall architecture. Here, in the below diagram you will come to know How MVC application behaves when it’s invoked from the browser. So, as you see in the diagram, as soon as request comes from the browser, it is picked up by the routing engine. Hence, ASP.NET Routing is the first step in MVC Life cycle. Basically it is a pattern matching system which matches the request’s pattern against the registered patterns in the Route Table. When a matching pattern found in the Route Table, the Routing engine forwards the request to the corresponding IRouteHandler for that request. If the routing engine doesn’t match the pattern then it returns 404 HTTP Status code.
Then, MVC handler implements IHttpHandler interface and further process the request by using ProcessRequest method. Then in third step MVCHandler uses the IControllerFactory instance and tries to get a IController instance. If successful, then Execute method is called. Now, once the controller has been instantiated, Controller’s ActionInvoker checks which action to invoke on the controller. Next, the action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JSONResult, FileResult, and EmptyResult. Now, the next step is the execution of the View Result which involves the selection of the appropriate View Engine to render the View Result. It is basically handled by IViewEngine interface of the view engine. Now, at last Action method returns a string, binary file or a JSON Formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser by using the current view engine.


Software Requirements:-
MVC 4 runs comfortably on any of the following windows Operating Systems.

• Windows 8
• Windows 7
• Windows Vista
• Windows XP
• Windows Server 2008 R2
• Windows Server 2008
• Windows Server 2003

MVC 4 tooling comes by default with Visual Studio 2012/13. This can also be installed on Visual Studio 2010 as well. However, if you are not having the professional version of Visual Studio, you can use free version of visual studio, Visual Web Developer Express from the Microsoft Site itself. If you’re using Visual Studio 2010, you can install MVC 4 using the Web Platform Installer

Application Glimpse:-
Now, before jumping to create our 1st MVC application, let me give you demo that what we are going to create here. So, below is the snapshot of “MovieReview” site in its finished form. If you look at the URL, you will notice that I have already deployed the same on Azure (Microsoft’s Cloud).


So, here we are at the home page listing couple of movies. It has got features like Paging, Async Search, Bootstrap Features and many more UI related stuffs which you will be exploring in the coming chapters.


Now, the above page is quite descriptive. So, when you click the Edit link corresponding to the movie, it will emit text in editable mode as shown below.


So, when you click on “Back to List”, it will take you to the Movies List back and from there if you click the “Details” link, it will give the movie details as shown ahead.


Now, from here also you can edit the record. Now, back from Movies List if you click on “Reviews” link, it will take you the below page.


So, from here you can obviously create a new review as well as shown in the screen shot.


Now, as you can see in the above screen shot as soon as user tried to enter a rating 6 which is greater than 5, it threw an error. So, at this point of time, you cannot submit this review. You need to fix this 1st and then submit as shown below.


So, as you can see in the above screen shot, as soon as I corrected the error, error description wiped out automatically. Now, I can go ahead and submit the record.


Now, if you click “Delete” option back from the list, then you will land up in the below shown delete page.


So, from here, you can go ahead and delete the page. Now, if you come back on the Movies List, you will notice that there is no option for creating the movie.


Well, for that I have made couple of changes like you should be authenticated 1st and authenticated as an admin, then only you will be able to see the Create Link. So, let me go ahead and login using my credentials.


Then, it will show me the below Create Link.


So, with that Create link, only admin users can go ahead and create the movies. So, this way I have restricted this action for anonymous users. Now, one more thing which I would like to show you is glimpse of my logging technique. I am a big fan of ELMAH Web UI which you learn in detail in coming chapters. But, for now just look at the glimpse of that. So, when you navigate http://mymoviereviews.azurewebsites.net/elmah, then it will produce you the application snapshot as shown ahead.


Currently, my application is running fine; hence it didn’t produce any error log. Like this there are many more features which you can delve while building the application right from the scratch. So, stay tuned and get ready to build your 1st MVC application end to end.

Also, after creating the web application, I have converted the same app to support mobile browsers as well. So, now, if you open the same site in your mobile phone, it will get stacked as per your mobile resolution. So, the application has become smart enough to figure out that it is getting invoked from which device. Now, below are screen shots of this sample application.



So, as you can see it has got different mobile user interface, and menu styling is also different. Also, the browser here I am using to test the same is opera mobile browser for desktop. Other features like collapsible panes as shown ahead fits very nicely with mobile devices.


On similar lines you can see other pages like movie and movie reviews as shown ahead.

19th 20th 21th

So, this was the application glimpse in a nutshell. So, during this entire course you will be learning how to build an End to End Application which will not only support desktop version browsers rather mobile as well.
Creating a MVC Application:-
I always believe to learn anything is to get started with the hands-on the same, so that way you will understand the practical approach of solving any problem statement. However, we’ll be building a simple web app for “Movie Review” where in I’ll walk you through all the tiny steps involved in building the site. So, let’s get started. Before we begin, we must install the prerequisites for making this app. Now, to create a MVC Application, open the Visual Studio, click on New Project and select the below mentioned project as shown in the snapshot.


Note: – Here am using Visual Studio 2013 Ultimate Version.

Now, as soon as you select the MVC 4 web application, it will present couple of different application templates option as shown ahead in the screen shot.


Empty Template: – Empty template will just have the basic folder structure that’s it and nothing more than that.
Basic Template: – The basic template will give you the MVC infrastructure in the solution. However, basic templates are for experienced MVC guys who want to customize the solution their way.
Internet Application: – Internet Application is the one which I am interested in as you can see in the above screen shot. However, it will give all the required dependencies in my solution structure to get started with my web application.
Intranet Application: – Intranet application is the one which deals with Windows Authentication. So, once you select this option, you app gets automatically configured with windows related settings.
Mobile Application: – Mobile application is the one which is included with MVC 4. The mobile application is preconfigured with JQuery Mobile. It helps developer to create just mobile sites. It includes themes which is supported by mobiles, touch enabled UI etc.
Web API: – Web API terminology will be discussed in detail later in this book. However, for now you just need to know that Web API is basically a framework which supports creating HTTP services.
Single Page Application: – SPA is a new terminology which offers building Single Page Application, focused mainly on client side interactions using tons of JavaScript and different JS Frameworks like Knockout, Durandal, Angular etc. This kind of web application is highly interactive and feature rich for ex: – Gmail, Outlook etc.
Facebook Application: – Facebook application is I would say a kind of API support which offers developer to use the Facebook API in their application to build a Facebook centric website. This is really a cool stuff.
Now, the next option which I have selected above is razor as view engine, so if I click on this dropdown I could see two options available as Razor and ASPX.


I also have a habit of checking Unit Test Project as you can see below in the screen shot. So, upon checking this checkbox, Visual Studio will create one more project for me in the solution which is going to be Test project. Here, I can go ahead and write my test cases against any specific module or scenarios.


So, when you click on the dropdown of Test framework, you will see only one test framework in there. However, Microsoft has given an option to developers to install their friendly testing framework like NUnit, XUnit, etc. So, once these frameworks will get installed, this will get added in the dropdown box.

How MVC Applications are Structured:-

Below is the snapshot of the MVC application structure. This gives a brief idea that how your simple MVC app is structured initially.


Below I have listed specific directories which are there in the solution and their meaning.
Models: – Section containing all the classes related to fetching the data and manipulating the same.
Views: – Section containing all the UI related stuffs. These are the ones which are going to be rendered based on controller’s action.

Controllers: – Section where in the entire controller classes are placed which basically handles all the incoming requests from the browser.
Scripts: – Section where in all the scripts related stuffs are placed.
Images: – Section where in all the images are placed which is used across your site.
Filters: – Section where in all the filters are placed. We’ll do deep dive usage of filters later in coming chapters.
App Data: – Section where in all the data files are stored meant for reading and writing the same.
App Start: – Section where in all configurable stuffs resides like Web API, Routing etc.

Note: – This is basic internet app MVC structure. However, please note that MVC Framework never enforces any kind of folders organization. You can obviously customize the folders your way, like in many enterprise projects Models go in a separate class library project just to make sure reusability. However, you could do higher level of separation, it entirely depend on you.

So, in this chapter we have just seen the overview of MVC, history of MVC and its different releases. We also understood that ASP.NET MVC is another technique of building web application, a completely different strategy rather stateless technique to build the web app. We have also seen the application glimpse which we are going to build right from the scratch and host the same on cloud. As we progresses module by module in different chapters your doubts regarding MVC development will be getting clearer.

Thanks for reading the same.

Download Link:- http://rahulsahay.com/Hands%20on%20With%20ASP.NET%20MVC.pdf


20,707 total views, 13 views today

24 thoughts on “Hands on with ASP.Net MVC

  1. Hello Rahul I am not able to view/ read your content under “Hands on with ASP.NET MVC tab” .I am a fresh graduate working for CSC India right now, but i have very less knowledge of C sharp code.Currently working as core developer for a windows application I want to expand my skills to web development( ASP.NET).Please help me get links where I can learn all these skills like MVC.I want to read your articles but not able to.

    • I can read each article without any problem as an anonymous user. Let me know which article exactly you are trying to read. may be if you are trying to read it from restricted network like from office, where in might be very limited access to outside sites, then it could be issue. Otherwise no issue…..Btw, my book on “Hands-On with ASP.NET MVC” is releasing by the end of this month. This one i have written from scratch keeping college passouts in mind. So, you can start from here itself….

    • I have not written any manual for the same. However, I have written one book for the same. This is complete hands-on with asp.net mvc. Book is getting released in 10 days time in all formats.


  2. Hi Raul,
    I revised some entries in your blog about your book and It looks very interesting. I want to purchase its digital versión but it’s an pdf or epub?


    (from Lima Peru)

  3. I just purchased your MVC 6 book (kindle version) from Amazon. Could you please tell me where I can get the source code for the book please

  4. You recognize as a result drastically in connection with the following topic, taught me to be singularly picture this at a wide range of various angles yuk numpang. The just like males and females usually are not intrigued apart from it is something related to Gaga! Your own personal stuffs pleasant. All of the time preserve it upwards!

    • I have used general conventions around EF. Nothing specific to 6 and 7 as this book was mainly targeted around MVC. so, will be eligible in both cases.

  5. Hi Rahul,
    I like your book, but I need the sample solution which you are explaining,
    It is available anywhere to download.

  6. Hi Rahul,

    I really enjoy your book “Hands on with ASP.Net MVC”. Could you please tell me why when I try to modify the default value
    of connectionString in web.config I have an exception thrown:

    An exception of type ‘System.Data.SqlClient.SqlException’ occurred in EntityFramework.dll
    but was not handled in user code

    Additional information: Directory lookup for the file
    “c:\users\serguei\documents\visual studio 2015\Projects\MovieReview\MovieReview\App_Data\MoviesReview.mdf”
    failed with the operating system error 5(Access is denied.).

    CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

    Looking forward to your reply,
    Thank you in advance


    • Thanks! But, From the error perspective, you need to dig around. But, one quick thing i can tell you about the error is, compatibility issue. As, to me, it looks like you are running the code on VS2015, where I think you are using MS-SQL 2012 or higher version. But, when i wrote this, this was SQL 2008, i guess. Hence, compatibility issue. I would suggest, create new db around that, rather attaching existing .mdf file and then update the connection string accordingly. Similar stuffs, need to be done for Entity Framework as well. You can also look go for bindingRedirect, if there is any versioning issue happens. There are many articles around this issue on stack overflow.

  7. of course appreciate your internet site however you ought to confirm the spelling in some of your content regularly cloud server india. Many of options are rife with punctuation troubles and I in discovering it pretty frustrating frankly conversely I’ll unquestionably are available again all over again.

    • This was the 1st book. And, here my publisher has done tons of mistake. Hence, snapped the deal with him and made the book free. There will be MVC 6 book available shortly, which will be rectified and updated version. Apologies for the same.

  8. Hi rahul.. firstly thanks for awesome mvc book..,im completely new to mvc…, while im travelling with your book i got an exception when i enter the 6th chapter JS & Ajax helpers can you tell me how can i solve this and the exception is {“The entity or complex type ‘MovieViewModel’ cannot be constructed in a LINQ to Entities query.”}
    can you tell me what are may be the reasons…

  9. You will have to figure out how to do both things yourself. It is possible to add brewing recipes, but I have no idea how. Furthermore every “specific effect” is different so you won’t find a guide on that anywhere.

Leave a Reply

Your email address will not be published.

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=""> <s> <strike> <strong>