MVC
MVC
ASP.NETMVC.TemplateintroductionCodeProject
11,523,229
online
Sign up members
for our 74,407
free weekly
articles
Q&A
Sign in
forums
lounge
Searchforarticles,questions,tips
MIT
Rate this:
4.81 45 votes
Introduction
As the name implies, it's a project starter template for ASP.NET MVC based solutions mainly for multi
paged enteprise solutions, which could change in the future if there will be need for it.
This project was born after working on maintaining and improving few MVC projects and seeing how
much of a headache these projects were bringing with them. All because of a bad project foundation,
which in the long run started to ruin program's design and maintainability even more and more. Even
though there are a lot of examples of good ASP.NET MVC practises on the web, collecting them all and
applying in the first applications is not an easy task.
Background
There are few rules this project will try to follow:
Simplicity a good indicator of any program is it's simplicity thus resulting in lack of code. Any new
ideas or findings on making code simplier to understand and use will be incorporated first. Hard to
understand code should be reported to theissue police at GitHub along with reasoning on why it
was hard to understand and use suggestions are welcome in the comments.
Activity by nowthere area lot of good projects which are no longer actively developed dead.
And it is very sad. MVC.Template will try to be in the loop for years to come.
Open this project will always be open sourced with MIT license. Use it, like it, hate it, do whatever.
Up to date any new releases of frameworks used in the project will always be updated to their
newest releases. So even though we all love MVC5, it will not be supported after vNext release will
be sufficient to replace it and so on.
Features
ModelViewViewModel architectural design.
Lowercase or normal ASP.NET urls.
Custom membership providers.
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
1/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
Project structure
MvcTemplate is used for keeping any project specific implementation, which can not reside in
other projects. Mainly it will be custom project components, which can not be easily reused because
of hard dependencies to other solution projects, like data access layer.
MvcTemplate.Components should only contain reusable components. It means no references to
anyMvcTemplate.Xxxxxproject, with an exception of MvcTemplate.Resources. This assembly is
intented to keep all the reusable "goodies" which are born while implementing a specific project. So
that it can be reused in the next projects and save us some more time for programming more
interesting code.
MvcTemplate.Controllers separates controllers and their routing configuration from other
assemblies. It's known that separation of controllers has some disadvantages like not being able to
generate strongly typed helpers with T4MVC. But until someone proves this approach wrong,
controllers will be separated.
MvcTemplate.Data hides data access layer implementation from other assemblies. So that
assemblies which are using data access layer would not have to reference frameworks like
EntityFramework. Or, know implementation details about domain model mappings with view
models.
MvcTemplate.Objects contains all domain and view model classes in one place. Any other classes
should not be here.
MvcTemplate.Resources keeps all our "beloved magic strings" in healthy environment. It is also
used for easy solution globalization.
MvcTemplate.Services is the assembly which does the main job. And by the main job I mean
managing program state, like creating, editing, deleting domain entities; sending emails; eating CPU
cycles and what not. This is where the processing logic should be, not in the controller. Controllers
should only act as a brainless routing switch based on services and validation outputs.
MvcTemplate.Tests yet another main reason why MVC applications become as bad as they are.
One of the main problem MVC architecture is trying to address is testability, and not testing MVC
application should be considered a sin. This assembly covers most ~99% of the solution asemblies
code base. Mainly through unit testing.
MvcTemplate.Validators separates all domain validation logic from controllers and their services.
So it can be reused in other controllers if needed e.g. account registration and profile update shares
same validation concepts.
MvcTemplate.Web and finally web assembly, which is kind of empty. Because it mainly consists of
UI representation views, styling sheets, scripts and other client side components.
Installation
Download one of the release versions fromGitHub, or clone developbranch to your computer.
Before opening the project run "RenameProject.exe" located in the project's root folder running it
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
2/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
later can cause some compilation problems, because of generated dll's and such. It will:
Set initial assembly version to 0.1.0.0.
Rename solution and projects.
Rename root namespace.
Rename company name.
It will ask for your desired root namespace and company's name. So entering project's root
namespace "Oyster" and company's name "Tegram". Would result in project structure like this:
Namespaces like:
Hide Copy Code
namespaceOyster.Controllers.Administration
namespaceOyster.Services
namespaceOyster.Objects
Next, open solution and build project but not run it, so that NuGet packages can be restored.
After NuGet packages are restored, open Package Manager Console and run "updatedatabase", on
Data project. This creates initial database in local SQLEXPRESS instance.
Project uses some of commonly used VS extensions, you should download them if you don't have
them already:
Web Essentials 201X css files are generated by using "Web Essentials" build in less
compiler. Other then that Web Essentials provides other good VS extensions for modern web
developers.
You may have already seen a lot of red text in "Package Manager Console", especially those
who are using VS2013. It comes from T4Scaffoldingnot fully supporting VS2013.
If you are using VS2012, change T4Scaffolding.Core version to 1.0.0.
If you are using VS2013, download and installWindows Management Framework 4.0.
Which is needed for VS2013 scaffolding to work.
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
3/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
Depending on your machine configuration you may need to enable powershell scripts
to be run on your machine by using "SetExecutionPolicy" command.
After all this your project should compile and run. Default admin username and password can be
found in EntityFramework configuration class under ~/Root
namespace/Data/Migrations/Configuration.cs.
publicclassAccount:BaseModel//AlldomainmodelsshouldinheritbasemodelwithsharedIdand
CreationDatecolumns
{
[Required]
[StringLength(128)]
[Index(IsUnique=true)]
publicStringUsername{get;set;}//Onlymemberdeclarations,nobusinesslogic
[Required]
publicBooleanIsAdmin{get;set;}
}
publicclassAccountView:BaseView//AllviewmodelsshouldinheritbaseviewwithsharedIdand
CreationDatecolumns
{
[Required]
[StringLength(128)]
[Index(IsUnique=true)]
publicStringUsername{get;set;}//Onlymemberdeclarations,nobusinesslogic
//Declaringonlyuservisiblefields.Sothat"IsAdmin"propertycannotbeeditedorover
postedbytheuser
}
Database
Registering newly created model with the database is relatively easy. First of all, new DbSet has to be
added to the main Context class:
Hide Copy Code
publicclassContext:DBContext
{
...
protectedDbSet<Account>Accounts{get;set;}//protectedisused,sothattestingcontext
caninheritthesamedatabasestructure
...
}
MVC.Template is using code first approach for database management, so after adding new DbSet to the
context you will need to run "AddMigration <your_migration_name>", followed by "update
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
4/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
publicstaticclassObjectMapper
{
...
publicstaticvoidMap()
{
Mapper.CreateMap<Account,AccountView>();//Creatingautomaticmapfromaccountmodelto
accountview
Mapper.CreateMap<AccountView,Account>();//Creatingautomaticmapfromaccountviewto
accountmodel
}
...
}
Controllers
Any new controller should inherit BaseController, which can be used as an extension point for every
controller. Also it keeps shared controller methods, like authorization and redirection to static pages e.g.
"404 not found", "403 unauthorized". Other controller bases include:
ServicedController for controllers with injected service instance,
ValidatedController for controllers with injected service and validator instances.
The one to choose should be obvious from your needs in a controller. All these controller bases are under
[GlobalizedAuthorize] attribute, so they will all be authorized by default.
Hide Copy Code
publicclassAccountsController:ValidatedController<IAccountValidator,IAccountService>//Using
ValidatedController,becausecontollerwillbeusingvalidatorandserviceinstances
{
...
[HttpGet]
publicActionResultEdit(Stringid)
{
returnNotEmptyView(Service.Get<AccountView>(id));//Gettingviewfromservice,and
returningaccountviewonlyifaccountwithgivenidstillexists,otherwiseredirectingtonot
foundpage.
}
[HttpPost]
[ValidateAntiForgeryToken]//Validateantiforgerytokenonallpostactions
publicActionResultEdit(AccountViewaccount)//ActionacceptingAccountViewclassfromthe
request
{
if(!Validator.CanEdit(account))//Onecalltovalidateeverythingaboutthemodel
returnView(account);//Returntosamemodelview,ifanyvalidationfailed
Service.Edit(account);//Otherwiseperformmodelmutationbyusingtheservice
returnRedirectIfAuthorized("Index");//Redirectingto"Index"action,onlythencurrent
userisauthorizedtoviewit,otherwiseredirecttohomepage
}
...
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
5/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
Services
Services are ment to keep business logic for changing domain model or doing other business tasks. One
service class should only "serve" one domain model, thus the name of the service should generally be
<Domain model name>Service e.g. AccountService, RoleService. In addition to that, every service should
have an interface which inherits IService.
Hide Shrink
Copy Code
publicinterfaceIAccountService:IService//Inheritingsharedserviceinterface
{
...
TViewGet<TView>(Stringid)whereTView:BaseView;//DefininggenericGetViewmethod,so
thataccountmodelcanbeautomaticallymappedtoanymappedview
voidEdit(AccountViewview);//Definingeditactionforaccountview
...
}
publicAccountService:IAccountService
{
...
publicTViewGet<TView>(Stringid)whereTView:BaseView
{
returnUnitOfWork.GetAs<Account,TView>(id);//Gettingaccountdomainmodelwithgivenid
fromthedatabase,andmappingittoTViewtype
}
publicvoidEdit(AcountViewview)
{
Accountaccount=UnitOfWork.To<Account>(view);//Mappingviewbacktomodel
UnitOfWork.Update(account);//Updatingaccount
UnitOfWork.Commit();//Commitingtransaction
}
...
}
Validators
Validators, unlike services are ment to hold all business validation logic for domain models. Validator
implementation follow the same pattern as services. Validation class for one domain model with validator
interface.
Hide Copy Code
publicinterfaceIAccountValidator:IValidator//Inheritingsharedvalidatorinterface
{
//Otheraccountvalidatorinterfacecode
BooleanCanEdit(AccountViewview);//Definingneededvalidationmethodsforaccountview
//Otheraccountvalidatorinterfacecode
}
publicAccountValidator:IAccountValidator
{
...
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
6/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
publicBooleanCanEdit(AcountViewview)
{
BooleanisValid=IsUniqueUsername(view);//Makinganycustomvalidationtotheview
isValid&=ModelState.IsValid;//AlwaysincludeModelStatevalidationcheck,sothat
controllerneverhastocallModelState.IsValid
returnisValid;
}
...
}
Views
Views should always be written for view models like "AccountView", "RoleView", but never for domain
models.
Hide Shrink
Copy Code
@modelAccountEditView
<divclass="widgetbox">
<divclass="widgettitle">
<spanclass="widgettitleiconfafathlist"></span>
<h5>@Headers.AdministrationAccountsEdit</h5>
</div>
<divclass="widgetcontent">
@using(Html.BeginForm())
{
@Html.AntiForgeryToken()@*Validatingantiforgerytokenonallpostactions.*@
<divclass="formgroup">
<divclass="controllabelcolsm12colmd3collg2">
@Html.FormLabelFor(model=>model.Username)@*Customlabelhelpertoadd
required'*'spansandlocalizinglabels.*@
</div>
<divclass="controlcontentcolsm12colmd9collg5">
@Html.FormTextBoxFor(model=>model.Username)@*Customtextboxhelpertoadd
necessaryattributes,likereadonlyonnoteditablefields.*@
</div>
<divclass="controlvalidationcolsm12colmd12collg5">
@Html.ValidationMessageFor(model=>model.Username)
</div>
</div>
<divclass="formgroup">
<divclass="formactionscolsm12colmd12collg7">
<inputclass="btnbtnprimary"type="submit"value="@Actions.Submit"/>
</div>
</div>
}
</div>
</div>
Globalization
Currently default language is English, in addition to that Lithuanian was added, just for an example of
multiple languages with different number and date formats in the system. You can easily disable Lithuanian
language by removing it from the Globalization.xml file and then you have time, removing it's resources or
replacing them with your language of choice.
Hide Copy Code
<?xmlversion="1.0"encoding="utf8"?>
<globalization>
<languagename="English"culture="enGB"abbrevation="en"default="true"/>
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
7/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
</globalization>
Leaving one language will remove any language selections in the system automatically.
Summary
In this article, I introduced you to MVC.Template, a starting project template for ASP.NET MVC based
solutions. And explained starting project structure, it's installation and basic code usage. More examples
can always be found in MVC.Template's codebase at GitHub. This project will be actively develop by me
and my colleagues at work. And hopefully become ASP.NET MVC project starting point for new and
experienced developers alike.
History
2015.04.12Updates, accordingly with v1.3.
2015.01.05Updates, accordingly with v1.2.
2014.11.09Updates, accordingly with v1.1.
2014.09.22 Initial article for v1.0
License
This article, along with any associated source code and files, is licensed under The MIT License
Share
EMAIL
No Biography provided
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
8/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
Go
First Prev Next
about updatedabase
dennyqiu 9Jun15 3:52
How can this template handle the need to read legacy data ?
without breaking it's own elegance and rationale !
Step by step instructions needed
if possible.
Thanks
Sign In ViewThread Permalink
Microsoft.Owin.Security
RegisterInstance<IAuthorizationProvider>(new
AuthorizationProvider(typeof(BaseController).Assembly));
Thanks!
Re: Microsoft.Owin.Security
Muchiachio 16May15 22:59
Re: Microsoft.Owin.Security
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
9/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
rghubert
17May15 3:24
Re: Microsoft.Owin.Security
Muchiachio 17May15 3:29
How to put icons in the aplication
AFMatambo 6May15 15:06
Hello muchiachio.
Could you tell me how I can incorporate icons in the application siteMap, datagrids, forms, etc. I
am trying to follow the pattern that you have used but I cannot get the new icons to appear in the
application. Except all that youve used previously in Administration area.
Is it possible that I have to download them and put them in a folder like it is done with the country
flags for localization of the application? Or do I have to make some reference anywhere in the
project?
Once again thank you very much for your kindness in sharing with us this great job and for giving
us a first class customer service without charging anything for it.
Hide Copy Code
<siteMapNodemenu="true"icon="fafauser"area="Medico"controler="Antecedentes"
action="Index">
<siteMapNodeicon="fafauser"area="Medico"controler="Antecedentes"action="Create"/>
<siteMapNodeicon="fafauser"area="Medico"controler="Antecedentes"action="Details"/>
<siteMapNodeicon="fafauser"area="Medico"controler="Antecedentes"action="Edit"/>
<siteMapNodeicon="fafauser"area="Medico"controler="Antecedentes"action="Delete"/>
</siteMapNode>
AF Matambo
6May15 1:26
Scaffolding
hahajoop 3May15 20:16
Hi,
thanks for your great template, I love using it.
I am using VS 2013, and can't get the scaffolding to work. When I add a view, the default template
seems to be used, also I can't find a way to add a new controller using scaffolding.
Can you help me?
Sign In ViewThread Permalink
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
10/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
Re: Scaffolding
Muchiachio 4May15 4:02
Re: Scaffolding
hahajoop 4May15 9:23
Views/Auth/_AuthAlerts.cshtml line 1!
rghubert 21Apr15 10:10
IEnumerable<String>errorMessages=ViewData.ModelState.SelectMany(state=>
state.Value.Errors).Select(error=>error.ErrorMessage);
AlertsContaineralerts=TempData["Alerts"]asAlertsContainer;
and above all, where the error messages come from. It looks like this is populated by the
HtmlExtensions somehow but still not clear. Any tips? Thanks!
Hi, thanks for the update. What is the pattern for adding a WebApi. Since BaseController is a
Controller and not an ApiController...?
Today it is fashionable the use of async and await to improve application performance according to
Microsoft recomendations. Is it possible to use this technology with this template? If so, can you
explain to beginners how to use it without breaking functionality that already exists in this
template?
I'll need to implement it in the T4 template so that new Controllers have it in place, I'll appreciate if
you implement it also in the T4 Code Templates.
Thank you very much.
AF Matambo
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
11/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
Re: Localization on db
Muchiachio 18Mar15 4:36
Re: Localization on db
Z@clarco 18Mar15 5:00
Re: Localization on db
Z@clarco 18Mar15 5:03
Re: Localization on db
Muchiachio 18Mar15 5:25
Re: Localization on db
Z@clarco 18Mar15 22:06
Re: Localization on db
Muchiachio 19Mar15 1:30
Re: Localization on db
Z@clarco 19Mar15 2:57
Re: Localization on db
Z@clarco 24Mar15 3:50
Re: Localization on db
Muchiachio 24Mar15 5:32
Suggestion: primary keys with clustered indexes
rghubert 7Mar15 5:54
Hi,
in order to make a DB migration to SQL Azure possible, it would be good if the primary keys were
declared as clustered indexes. Otherwise, the following errors arise upon migration. I changed them
to clustered indexes and the import works now and hopefully the application too!.
Thanks!
Hide Copy Code
Oneormoreunsupportedelementswerefoundintheschemausedaspartofadatapackage.
ErrorSQL71564:TableTable:[dbo].[Accounts]doesnothaveaclusteredindex.Clustered
indexesarerequiredforinsertingdatainthisversionofSQLServer.
ErrorSQL71564:TableTable:[dbo].[Roles]doesnothaveaclusteredindex.Clustered
indexesarerequiredforinsertingdatainthisversionofSQLServer.
ErrorSQL71564:TableTable:[dbo].[RolePrivileges]doesnothaveaclusteredindex.
ClusteredindexesarerequiredforinsertingdatainthisversionofSQLServer.
ErrorSQL71564:TableTable:[dbo].[Privileges]doesnothaveaclusteredindex.Clustered
indexesarerequiredforinsertingdatainthisversionofSQLServer.
ErrorSQL71564:TableTable:[dbo].[Logs]doesnothaveaclusteredindex.Clustered
indexesarerequiredforinsertingdatainthisversionofSQLServer.
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
12/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
(Microsoft.SqlServer.Dac)
9Feb15 5:11
It's just perfect for starting a new project! Very good job!
I would like to use your template but I was wondering why you didn't use Identity2.0 and the builtin
role Model?
Thanks again for this great template!
Kind Regards,
Sign In ViewThread Permalink
9Feb15 21:54
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
13/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
9Feb15 23:22
In the business world, even in small ones, the management of user accounts is made by an
administrator at the request of the head of human resources in such a way that when an employee
sign a new contract then the admin opens new account and when the contract ends the
corresponding account is closed, may be using Delete or blocking procedure, preferably the better
and cautious way is blocking the access to the system for preventing a cascading deletion of
important business data that an employee has created .
It would be great and extremely useful to be maintained in this template this scenario of creation
and account lockout, and when the user login verify not only the account existence but also that
this user is enabled for system access.
On one occasion I saw a Boolean property, concerning the verification of a user account if it is
active or not, currently I dont see it implemented. Forgive me if this scenario is already
implemented in some way and I am not being able to see in what way is it implemented. If this is a
case please, I would appreciate that you tell me how I can apply it.
If it is not implemented we would greatly appreciate an implementation in this regard in the next
releases.
In same way it is needed to force the password expiration and allow change every 90 or 180 days
for example, and if the accounts password expired without password change lockout the account.
Also is needed to limit the login intents to 3 5 for example, and after that, deny the account
Access to system until it is enabled by the Sys Admin User.
Please can you add this functionalities in the next future?
Sincerely thank you very much for helping us mostly for who comes from Windows Form world and
get in touch for first time with MVC technology.
Once again thank you.
AF Matambo
Re: User Account Creation, Registering and Blocking by Sys_Admin needed implementation
Muchiachio
19Jan15 6:23
14/15
6/11/2015
ASP.NETMVC.TemplateintroductionCodeProject
AFMatambo
20Jan15 18:14
Is it possible to Localize the strings of the options of grid filter Equals, Contains, StartsWith,
EndsWith?
Thank you.
AF Matambo
1 2 3 Next
News
Suggestion
Question
Bug
Answer
Joke
Rant
Admin
Select Language
http://www.codeproject.com/Articles/820836/ASPNETMVCTemplateintroduction
15/15