Pro ASP.NET MVC 3 Framework

Adam Freeman, Steven Sanderson

Mentioned 28

The ASP.NET MVC 3 Framework is the latest evolution of Microsoft’s ASP.NET web platform. It provides a high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility, combined with all the benefits of ASP.NET 4. In this third edition, the core model-view-controller (MVC) architectural concepts are not simply explained or discussed in isolation, but are demonstrated in action. You’ll work through an extended tutorial to create a working e-commerce web application that combines ASP.NET MVC with the latest C# language features and unit-testing best practices. By gaining this invaluable, practical experience, you’ll discover MVC’s strengths and weaknesses for yourself—and put your best-learned theory into practice. The book's authors Steve Sanderson and Adam Freeman have both watched the growth of ASP.NET MVC since its first release. Steve is a well-known blogger on the MVC Framework and a member of the Microsoft Web Platform and Tools team. Adam started designing and building web applications 15 years ago and has been responsible for some of the world's largest and most ambitious projects. You can be sure you are in safe hands. What you’ll learn Gain a solid architectural understanding of ASP.NET MVC 3, including basic MVC Explore the entire ASP.NET MVC Framework See how MVC and test-driven development work in action Capitalize on your existing knowledge quickly and easily through comparison of features in classic ASP.NET to those in ASP.NET MVC Learn about the latest security and deployment issues, including those related to IIS 7 Who this book is for This book is for web developers with a basic knowledge of ASP.NET and C# who want (or need) to start using the new ASP.NET MVC 3 Framework. Table of ContentsPart 1 1. The Big Idea 2. Getting Ready 3. Your First MVC Application 4. The MVC Pattern 5. Essential Language Features 6. Essential Tools for MVC 7. SportsStore I – A Real Application 8. SportsStore II – Navigation & Cart 9. SportsStore III - Administration Part 2 10. Overview of MVC projects 11. URLs, Routing & Areas 12. Controllers & Actions 13. Filters 14. Controller Extensibility 15. Views 16. Model Templates 17. Model Binding 18. Model Validation 19. Unobtrusive Ajax 20. jQuery Part 3. 21. Security 22. Authentication & Authorization 23. Deployment

More on

Mentioned in questions and answers.

I have a project that requires my URLs have dots in the path. For example I may have a URL such as

URLs with the dot generate a 404. My routing is fine. If I pass in michaelphelps, without the dot, then everything works. If I add the dot I get a 404 error. The sample site is running on Windows 7 with IIS8 Express. URLScan is not running.

I tried adding the following to my web.config:

  <requestFiltering allowDoubleEscaping="true"/>

Unfortunately that didn't make a difference. I just receive a 404.0 Not Found error.

This is a MVC4 project but I don't think that's relevant. My routing works fine and the parameters I expect are there, until they include a dot.

What do I need to configure so I can have dots in my URL?

You might want to think about using dashes instead of periods.

In Pro ASP MVC 3 Framework they suggest this about making friendly URLs:

Avoid symbols, codes, and character sequences. If you want a word separator, use a dash (/my-great-article). Underscores are unfriendly, and URL-encoded spaces are bizarre (/my+great+article) or disgusting (/my%20great%20article).

It also mentions that URLs should be be easy to read and change for humans. Maybe a reason to think about using a dash instead of a dot also comes from the same book:

Don't use file name extensions for HTML pages (.aspx or .mvc), but do use them for specialized file types (.jpg, .pdf, .zip, etc). Web browsers don't care about file name extensions if you set the MIME type appropriately, but humans still expect PDF files to end with .pdf

So while a period is still readable to humans (though less readable than dashes, IMO), it might still be a bit confusing/misleading depending on what comes after the period. What if someone has a last name of zip? Then the URL will be / instead of /John-zip, something that can be misleading even to the developer that wrote the application.

I want to get started using Dependency Injection and IOC and I want to get more into using Ninject.

Are there any good application with sourcecode available that is written using Ninject that I can look at as a reference?

I would recommend the book Pro ASP.NET MVC 3 Framework. It has some excellent samples and explanations on how to implement Ninject as well as Moq and Unit Testing, in an easy-to-read format that doesn't make you feel like a Dummy.

So after much screwing around I finally got Ninject wired in and compiling in my MVC4 application. The problem I was running into is the IDependencyScope interface no longer exists from what I can tell and the System.Web.Http.Dependencies namespace was done away with.

So, my problem now is I have everything wired in and upon running the application I get:

    Sequence contains no elements

    [InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.Single(IEnumerable`1 source) +379
   Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectMvcHttpApplicationPlugin.cs:53
   Ninject.Web.Common.Bootstrapper.<Initialize>b__0(INinjectHttpApplicationPlugin c) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:52
   Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) in c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:31
   Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:53
   Ninject.Web.Common.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\NinjectHttpApplication.cs:81

Which I haven't been able to track down or even begin to fathom where it is coming from.

My standard Ninject methods inside the Global.asax.cs look as follows:

        protected override IKernel CreateKernel()
            var kernel = new StandardKernel();

            GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NinjectDependencyResolver(kernel));
            return kernel;

        protected override void OnApplicationStarted()

And my custom resolver:

public class NinjectDependencyResolver : IDependencyResolver
    private readonly IKernel _kernel;

    public NinjectDependencyResolver(IKernel kernel)
        _kernel = kernel;

    public object GetService(Type serviceType)
         return _kernel.TryGet(serviceType);

     public IEnumerable<object> GetServices(Type serviceType)
             return _kernel.GetAll(serviceType);
         catch (Exception)
             return new List<object>();

     public void Dispose()
         // When BeginScope returns 'this', the Dispose method must be a no-op.

Any insight here would be greatly appreciated. I've spent far too much time already trying to get any DI framework wired into the latest MVC4 RC running on .NET 4.5 and have now just reached my tolerance level for things just not working at all..

Edit #1 A little further research digging around in github the ExtensionsForIEnumerableOfT.cs doesn't help much:

And possibly if I had wrote it myself I would begin to understand this but Bootstrapper.cs doesn't help too much either.

Hoping these details will make it easier for any of you who might have more experience with Ninject.

Edit #2 The error encountered is specifically in NinjectMvcHttpApplicationPlugin.cs:

The offending line is:


Which lives in the following method:

public void Start()

The ModelValidatorProviders collection contains 2 elements: {System.Web.Mvc.DataErrorInfoModelValidatorProvider} {System.Web.Mvc.ClientDataTypeModelValidatorProvider}

And it's trying to remove a single instance of:


Which apparently isn't loaded up in the ModelValidationProviders.Providers collection. Any ideas from here?

Resolution to Above Exception And Onto The Next

To resolve the issue in the ModelValidatorProviders I had to manually add an object it was expecting. So now my CreateKernel method looks like:

protected override IKernel CreateKernel()
    var kernel = new StandardKernel();


    GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NinjectDependencyResolver(kernel));
    ModelValidatorProviders.Providers.Add(new DataAnnotationsModelValidatorProvider());
    FilterProviders.Providers.Add(new FilterAttributeFilterProvider());
    return kernel;

Now it runs and gets into the actual guts of Ninject but still has an issue, one that makes no sense yet again:

Exception Details: Ninject.ActivationException: Error activating IntPtr
No matching bindings are available, and the type is not self-bindable.
Activation path:
 3) Injection of dependency IntPtr into parameter method of constructor of type Func{IKernel}
 2) Injection of dependency Func{IKernel} into parameter lazyKernel of constructor of type HttpApplicationInitializationHttpModule
 1) Request for IHttpModule

 1) Ensure that you have defined a binding for IntPtr.
 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
 3) Ensure you have not accidentally created more than one kernel.
 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
 5) If you are using automatic module loading, ensure the search path and filters are correct.

Check out the Pro ASP.NET MVC 3 book. I just ported this code over from MVC3 to MVC4 last night and works correctly. Page 322 to be exact.

What I don't see is where you are mapping your Interface to your concrete items.


Add another constructor and add the method that calls your mapping;

public NinjectDependencyResolver() {
    _kernal = new StandardKernel();

public static void RegisterServices(IKernel kernel) {

Here's what a resolver could/should look like;

   public class NinjectDependencyResolver : IDependencyResolver {
    private IKernal _kernel;

    public NinjectDependencyResolver(){
        _kernal = StandardKernal();

    public NinjectDependencyResolver(IKernel kernel)
        _kernel = kernel;

    public object GetService(Type serviceType)
         return _kernel.TryGet(serviceType);

     public IEnumerable<object> GetServices(Type serviceType)
        return _kernal.GetAll(serviceType);

    public IBindingToSyntax<T> Bind<T>() {
      return _kernal.Bind<T>();

     public static void RegisterServices(IKernel kernel){
      //Add your bindings here. 
      //This is static as you can use it for WebApi by passing it the IKernel

Global.Asx -



DependencyResolver.SetResolver(new NinjectDependencyResolver());

That's it.

UPDATED 11/14/2012

On a side note, if you're working with MVC WebAPI, you will want to use WebApiContrib.IoC.Ninject from nuget. Also, check out the "Contact Manager" in their samples This helped to cleanup the implementation of Ninject

What is a good MVC 3 tutorial for beginner/intermediate/Advanced?

Definitive and authoritative sources are preferred.

Either websites or books are fine.

the ASP.NET MVC site is a decent tutorial to get started with (MVC Music store) as it shows the basics but I can suggest the following books as well:

I think it's important to point out here that the tutorials are a good starting point - they will not make you an expert. It will be through external reading and practice that MVC will feel "easy" to you. Remember though, there are other books, these are just 2 from the ones I know and have read

Are there any books / tutorials on jQuery with ASP.NET MVC 3? I need to learn how to use ajax links and how to submit ajax forms ect. If there aren't any books / tutorials on MVC 3 yet MVC 2 wil also suffice.

P.S I do know how to do basic stuff with the MS AJAX Toolkit that comes with MVC

I think I found the official documentation at but that seems pretty useless compared to the blog posts from the developers and compared to other projects such as Zend Framework and Ruby on Rails.

I found the source code at where they are saying "For more details about ASP.NET MVC 3, please visit" so is this the official place?

So where is the official documentation? Where can I find the api guide? Where can I find the Issue tracker?

(I was only allowed to send one hyperlink in this post since I am a new user)

I want to ask experienced ASP.NET developers about how to climb the learning curve of ASP.NET.

I am an experienced C++ and C# developers with no web application experience.

I found ASP.NET MVC and ASP.NET are two different technologies. I just want to ask:

  1. Whether these two technologies will co-exists or MVC will replace ASP.NET?
  2. If I want to learn ASP.NET MVC. Do I need to learn ASP.NET as a prerequisite?
  3. Can you recommend some learning resources? Book? Video? Not paid Microsoft training :(

Many thanks

Can't say if one is going to rule the other one out. But the easiest to learn is MVC. Pro ASP.NET MVC 3 Framework

this is a good book to learn it.

Let's say I have a Web application implemented like a set of wizard pages to edit a complex object. Until the user clicks on the "Finish" button, the object doesn't get saved to the back-end system (a requirement), so in the meantime I have to keep the whole information about the object in some kind of a session state.

Also, some of the wizard pages have to show combo and list boxes with potentially large number of items. These items are fetched from the back-end system using a Web service.

Coincidentally, the wizard allows the user to freely jump from one wizard page to any other (using tab links on top of the form), so it's not a simple "next, next... finish" thing.

Additional constraint: the Web application runs on a Web farm and the customer is weary of using server-side session state. In the best case they want to keep the size of the session state minimal (they had problems with this in the past).

So basically there are two problems here:

  1. How/where to keep data entered by the user in the Wizard?
  2. Whether to cache the combo/list items received from the back-end and if so, where?

Options I'm considering:

  1. Storing the object in a WebForms-like ViewState (by serializing it into the HTML page). This would also include the combo box items. Obviously, there could be a problem with HTML pages becoming very large and thus Web application will be slow.

  2. Storing it into server-side session state, regardless of the customer's wishes and without knowing how the performance will be affected until it is tested on the actual Web farm (late in the project).

I cannot decide between the two. Or is there another alternative?

The answer to this can be found in Steve Sanderson's ASP.NET MVC 2/3, and requires a reference to the MVC Futures assembly. This link to Google Books is exactly what he does.

In essence, you serialize the wizard data to the View. A hidden field is rendered storing all of the acquired information.

Your controller can work out what to do through the use of the OnActionExecuting and OnResultExecuted (to cater for redirects) to pass it to the next view.

Have a read - he explains it much more thoroughly than I can.


Should i put service layer and repository layer into one project, so the web project is able to reference to DbContext objects ? Now my web(controllers) are unable to reference to dbcontext objects. what is the right way?

// service and repository are together
(View <- Controller) -> (Service -> Repository -> EF DbContext) -> (DB) 
// separate service and repository layer
(View <- Controller) -> (Service) -> (Repository -> EF DbContext) -> (DB)

Below are original question

i know SO is an excellent community to post my questions about mvc design patterns. Please give me your advice and I will appreciate your help. Thank you!

We are planning for a new project and our priority is to develop an application that is extensible and loosely-coupled.

I am new to software development; I did some reading on MVC Music Store Tutorial, and followed by a book called Pro ASP.NET MVC 3 Framework by Steven Sanderson (Apress),From the book, I learnt about DDD(Domain driven design) and some other concepts like repository and dependency injection. I have followed the book to build the SportsStore website, and gained some basic understanding about DI. But I personally think that the example did not separate the business logic layer, so i did a research on that, i found a pattern called Service Layer Pattern, and from what i understand, it separates the Business logic layer. Based on this, I came out with a structure for my new project(sample project below).

Do i need to implement IDisposable interface? if yes, where and why? Is this structure feasible for a relatively big-scale project?

sample database design: Product(one)----(many)ProductCategoryRs(many)----(one)Category

the solution contains 3 projects: Repository,Service,Web


Define IRepository interface , basic CRUD operations

Are these signatures sufficient? Should I add TEntity GetById(object id);?

public interface IRepository<TEntity>
    IQueryable<TEntity> All { get; }
    void Create(TEntity item);
    void Update(TEntity item);
    void Delete(TEntity item);
    void SaveChanges();

Implement generic Repository class

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
    STOREEntities context;
    public Repository()
        context = new STOREEntities();
    public IQueryable<TEntity> All
            return context.Set<TEntity>();
    public void Create(TEntity item)
    public void Update(TEntity item)
        context.Entry<TEntity>(item).State = System.Data.EntityState.Modified;
    public void Delete(TEntity item)
    public void SaveChanges()

Service: Define IProductService interface, extend business logic here.

public interface IProductService
    IEnumerable<Product> Products { get; }
    IEnumerable<Product> Get(Expression<Func<Product, Boolean>> filter);
    Product GetByProductId(int productId);
    void AddProduct(Product product);
    void EditProduct(Product product);
    void RemoveProduct(Product product);
    void SaveChanges();

Implement Product Service

    public class ProductService : IProductService
    IRepository<Product> repository; //Inject
    public ProductService(IRepository<Product> repo)
        repository = repo;
    public IEnumerable<Product> Products
        get { return repository.All; }
    public IEnumerable<Product> Get(Expression<Func<Product, bool>> filter)
        return repository.All.Where(filter);
    public Product GetByProductId(int productId)
        return repository.All.SingleOrDefault(p => p.ProductID == productId);
    public void AddProduct(Product product)
    public void EditProduct(Product product)
    public void RemoveProduct(Product product)
    public void SaveChanges()

Web project, retrieve data from service and convert to viewmodel and display. ProductController code

public class ProductController : Controller
    IProductService productService; //inject
    public ProductController(IProductService service)
        productService = service;
    public ActionResult Index()
        var products = productService.Products; //retrieve from service layer
        return View(products);

I believe you really should add a TEntity GetById(int id) to your IRepository<TEntity> generic interface.

Why? Because if you don't, and if you want to fetch a single record on your business layer, you only have two options (on the repository, data-access layer):

  1. Return a complete, "unlazy" collection, meaning that you'll return, say, 100,000 records in order to use a single one.
  2. Return a lazy collection like IQueryable<TEntity>, which, yes, will allow you to get a single record from the database, but may cause a lot of nasty side-effects.

The first option is clearly wrong. The second is controversial, but (unless your project has you as a single developer, and you really really really know what you're doing) it is potentially leaky and unsafe. So, if you do need a single record (and sometimes you'll surely do), expose a method that does exactly that.

Having said that, you should also not expose IQueryable<TEntity> All { get; }, for exactly the same reasons above. Use IEnumerable<TEntity> All { get; } instead, and make your concrete generic repository class return a real collection, by calling context.Set<TEntity>().ToList() for instance.


Regarding IDisposable:

There are only two (related) reasons for implementing the IDisposable interface that I can think of:

  1. Disposing unmanaged resources
  2. A cool way of implementing the RAII pattern.

In your case, you probably should use it on your repository implementation. Please take a look at this SO question for further information.

Are there any books that anybody would recommend to learn NHibernate and ASP.NET MVC v3?

I know that there are a lot of good tutorials online (feel free to recommend any), but I also like to learn from books, so any recommendations will be greatly appreciated.

For the MVC3 side of the equation, Pro ASP.NET MVC3 by Adam Freeman and Steven Sanderson is outstanding. The material is comprehensive, and each chapter includes great unit testing examples. What I especially loved was that "advanced" topics like integrating an IoC framework for controller creation was covered early.

Incidentally, one of the authors, Steven Sanderson, is the creator of KnockoutJS, which is one of the most impressive JavaScript frameworks out there.

For NHibernate it's a bit trickier. I read NHibernate in Action, which was outstanding, but that's a bit dated now. I don't see many titles that cover the newer NH3 with linq.

I just began working on an application with a couple areas (basic grid master / details type system..) I'm looking into taking advantage of the nice routing features in MVC (4 specifically) and I'm "just not getting it" I presume.

Currently the only route defined is the basic one:

            new { controller = "Account", action = "Index", id = UrlParameter.Optional }

which is fine, it works with the areas we have defined, so I'm assuming it must know where the user is and route to the appropriate controller based contextually on the location / area that the user is in.. so far nice..

Now, i'm trying to set up a new route that can handle


and specifically something like:




where "New" is the "New" status and have the Action Signature look like:

public ActionResult List(string statusName)

i was assuming I could just add the new route below the default one identifying "statusName" instead of Id, but of course, how the H would the routing mechanism know the difference between :



I did try adding a "static" route in the form of

            new { statusName = UrlParameter.Optional }

I thought I could "hiJack" just that one route and do something special with it, but to know avail, the router stops at first match?? I'm assuming that was the wrong way to address this issue anyhow..

so now I'm going through the idea of getting to something like:


ex. /OrderManagerList/viewNew

where these routes would basically be "aliases". I had thought that adding the following route would do the trick:

          new {controller="OrderManager", action="List", statusName= UrlParameter.Optional }

with the associated action on the OrderManager controller:

public ActionResult List(string statusName)

no matter what I try, the argument is null, or the "resource cannot be found"

I know the controllers need to have a corresponding View file.. but that's not the issue here, the issue is my attempt at understanding the routing..

SO my questions.. fundamentally, what am I missing about the routing in MVC (4)? even some good articles for a simpleton like myself to understand?

my understanding; define a route, and map it's "endpoint".. however, i think i'm not understanding the assumptions that the machine is making..

anyhow, let me know if further explain / edit is required..

thanks in advance.

The basic principle of routes is that they are evaluated from the top down, and the routing systems uses the first match, not the best match.

The implication of this is that you must order your routes in order of specificity, with the most specific route first and the most general route last.

With this principle in mind, let’s look at your situation. Initially, you have only the default route defined:

        new { controller = "Account", action = "Index", id = UrlParameter.Optional }

The URL pattern is "{controller}/{action}/{id}". By itself, this would match any three-segment URL, and would not match any URL that had less than three segments. However, the third input parameter is the default parameter, which defines defaults for the first and second segment and indicates that the third segment is optional. The next effect of this is to make the route match URL having 0,1, 2 or 3 segments.

Now you want to add a route where the third URL segment is mapped to a “statusName” parameter, and can handle URLs like:


There are two basic approaches you can take here. You can 1) create a very specific route that will handle these two URLs only, or 2) you can try and create a more general route to handle the general case. Let’s look at the first case first. You can create a route as follows:

routes.MapRoute("", "OrderManager/List/{statusName}",
              new { Controller = "OrderManager", Action = "List" });

Note that because this route is more specific than the default route, you must put this route before the default route.

If you want to have a more general route, you need to decide how this route will differ from the default route, since they both will match URLs having three segments. Let’s say you decide that the new route will accept anything that only contains letters in the third segment, leaving the default route to handle anything containing numbers. You can do this using route constraints. For example you could write a route as follows:

            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            constraints: new { id = @"^\d+$" });

            name: "NewRoute",
            url: "{controller}/{action}/{statusName}",
            defaults: new { Controller = "OrderManager", Action = "List" },
            constraints: new { statusName = "^[A-Za-z]+$" });

With these two routes, any three-segment URL having only letters in the third segment will put the third segment into a variable called “statusName”, whereas any URL with an integer in the third segment will put the third segment into a variable called “id”.

In any applications of real complexity, routes can get complicated, and it is very advantageous to write unit tests for your routes, to insure that you don’t screw things up when you add or modify a route.

For good references on routing, see Scott Sanderson's book or see the MSDN documentation

If I want to combine using repositorys per entity and Viewmodels per view how does it work out?

Any website tips I could look up? Maby someone could give an easy example?


Best Regards!

I like the following structure (from the famous Steven Sanderson's Pro ASP.NET MVC series):

Domain Project (Business Logic):

  • Abstract Folder (repository interfaces)
  • Concrete Folder (repository implementations)
  • Entities (EF generated classes)

Web UI Project (MVC Web App):

  • Models (view models)
  • Views
  • Controlers
  • etc, you get the point

The main thing is you're separating your business logic (which should house your repositories) from your Web UI (the MVC project)

In this scenario, your Controller classes reference the domain layer and use DI/IoC to call up the correct instance of the repository.

Example controller class:

namespace MyMvcProject
    using System.Whatever;
    using MyDomainLayer;

    public class MyController : Controller
        private readonly IMyRepository _myRepository;

        public MyController(IMyRepository myRepository)
            // Resolved using your favorite DI/IoC Container:
            this._myRepository = myRepository;

        public ActionResult DoSomething()
            var stuff = _myRepository.GetStuff();
            return View(stuff);

I have been developing .NET applications for two years and now I want to learn new technologies in that.

I have noticed many people now prefer developing applications with MVC because it is easy to maintain and is more testable.

I tried to look at it but I found the coding bit different than the normal c# coding.

Can some body please suggest the best way to start learning MVC?

Do I need to learn MVC first, then MVC2 and MVC3?

Do I have to use to use n-hibernate or linq for database connectivity? (Because I don't know any of them)

Please Suggest.

Many Thanks

I think is a good start to learn ASP.NET MVC. Also, I'd recommend to buy a good book such as Pro ASP.NET MVC 3 Framework.

You don't have to use nHibernate or linq2SQL. You can use whatever ORM or data access technology you like best.

Also you don't need to learn MVC 1/2 first. Start directly with the current version.

Good day!

I've a model that is binded from JSON request, say like this:

public class MyModel
     public bool isSomeFeatureEnabled { get; set; }

And controller like this:

public ActionResult Submit(MyModel request)
    if (ModelState.IsValid)

When I post empty JSON object to this action ({}) it will be valid with isSomeFeatureEnabled=false. But I want this field 'required' in terms that it should be set always in particular value (true\false).

I can make this field nullable and put [Required] on it, but the field is not really nullable per model logic.

The same story with int, double and DateTime fields.

I use ASP.NET MVC 3 and default setting of:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = true

Shouldn't it work for this situation?

I think making this field nullable and also making it Required is the best shot for now. As the book states, . Otherwise, you can write your own attribute, make the validate method return false when passed in value = default(T)

I have an MVC 3 application. I have a model called UserModel that contains an email field, validated for unique with RemoteAttribute. I want to use UserModel on 2 Views - EditUser and CreateUser. How can I permit validation of email field on EditUser view(because there this field is readonly), and leave it on CreateUser view?

You can use the partial validation technique to modify the validation results. This example will discard any errors for the Email field.

public class DontValidateEmailAttribute : ActionFilterAttribute {

  public override void OnActionExecuting(ActionExecutingContext filterContext) {
    var modelState = filterContext.Controller.ViewData.ModelState; 
    var incomingValues = filterContext.Controller.ValueProvider;

    var key = modelState.Keys.Single(x => incomingValues.Equals("Email"));    


and apply this attribute to your Edit Controller.

I learnt this technique from Steve Sanderson's Pro ASP NET MVC 3. He uses the technique to validate a model that has required fields but the data entry is a multistep wizard. If the value has not been returned in the form post, he removes the errors for that property.

I'm interested in learning about the MVC3 framework.

My background is MSc in Computer Science, with a professional experience in .NET2-4 and WebForms. I also have (very) little experience with MVC2, and some decent experience with JS and jQuery if that matters

I'm unsure which book to purchase to get me well off.

I've seen this book, Pro ASP.NET MVC 3 Framework, recommended in a few threads but its reviews are less than stellar. Including "Many errors in code", "lots of typos", "seems to be rushed out to be the first book on the subject". Therefore, I am reluctant to just go and buy this book in its first edition.

It seems the options are limited to

And ofcourse, just looking at NerdDinner but I feel I'll probably miss a lot of cool features by taking that road...

Offhand note: I have no interest in learning Entity Framework at the moment.

What would be SO's recommendations for such a book?

I have the first book and posted a review of it on Amazon.

Overall it is a decent book that does a good job, but there are issues as mentioned in my review and others.

I would still recommend you get it as a starter though as for me it has been a great starter into MVC.

We have a custom templating framework used by our web applications with implementations which are written in a variety of languages, and I'm investigating whether its possible to use this in an ASP.NET MVC application using the Razor View engine. We already have an implementation that uses the Web Forms View engine, but I'm keen to be able to use Razor as well.

The template is defined in a html file which contains macro tags that are interpreted and replaced at runtime with the applicable html. Below is a highly simplified version of this file:-

  <body id="[if Home][Home][else]body[end if]">
    [end form] 

As you can see, there are opportunities to inject html into various sections of the document, with some of this being handled by a simple conditional logic implementation. In order to use this with Razor, I'd need to be able to process all the macro tags in the template, including inserting the HTML from the Razor view being rendered, and use the output of this operation as the HTML to be ultimately sent to the client.

I'm pretty green when it comes to MVC development, but I know I can create a custom ViewEngine and IView implementation. Perhaps I can use this to achieve what I want, with a custom engine using the RazorView class to render the actual content to be inserted into our template. Does this sound like a feasible solution? And if so, does anyone have any tips to get me started?

Currently I have a kludgy solution where I use the ASP.NET WebForms engine and render partial Razor views, but longterm I'd prefer to have a solution that can take the WebForms engine out of the equation entirely.

Any shoves in the right direction greatly appreciated.

I've managed to figure something out. Although my problem is not exactly the same you have, but it can certainly help you. But first things first.

The problem

I have a number of controls (in my case they are Partial Views). For example:


I want to define groups of these controls (in database or web.config), for example:


Then I want to render a view based on a particular group. I was thinking the following syntax would be sufficient.

@Html.Partial("ControlGroup:ExtendedEditGroup", Model)

Draft of the solution

I wanted to create my own render engine which will do the following:

  1. If the name of the view begins with "ControlGroup:" then use previously defined groups to render the page. Each of the controls should be rendered by RazorViewEngine.
  2. If the name of the view doesn't begin with "ControlGroup:" just let the RazorViewEngine do its work.


I've found following resources:

  1. Article on CodeProject - Custom ViewEngine in ASP.NET MVC3
  2. Article based on StackOverflow question - Creating a Widget system in ASP.NET MVC 3
  3. I recommend you the book Pro ASP.NET MVC 3 Framework. It will give you the idea how many things you can customize in ASP.NET MVC 3
  4. Of course source code of ASP.NET MVC 3 RTM was very helpful.

Final solution


public class MyViewEngine : RazorViewEngine
  IDictionary<string, List<string>> groups = new Dictionary<string, List<string>>();

  public MyViewEngine()
    // Temporary data source
    groups["SimpleEditGroup"] = new List<string>() { "EditName"};
    groups["ExtendedEditGroup"] = new List<string>() { "EditName", "EditEmail"};

  public override ViewEngineResult FindView(ControllerContext controllerContext,
           string viewName, string masterName, bool useCache)
    if (viewName.StartsWith("ControlGroup"))
      var groupName = viewName.Split(':')[1];
      var controls = new List<ViewEngineResult>();

      foreach (var controlName in groups[groupName])
        // Find each control using Razor magic
        var control = base.FindPartialView(controllerContext, controlName, useCache);
        if (control.View != null)

      if(controls.Count > 0)
        return new ViewEngineResult(new MyView(controls), this);

    return base.FindView(controllerContext, viewName, masterName, useCache);


public class MyView : IView
  IList<ViewEngineResult> controls;

  public MyView(IList<ViewEngineResult> _controls)
    controls = _controls;

  public void Render(ViewContext viewContext, TextWriter textWriter)
    // For simplicity I used table for layout
    textWriter.Write("<table border='1'>");

    foreach (var ctrl in controls)

      // Render control using Razor
      ctrl.View.Render(viewContext, textWriter);



Don't forget to register your new engine in Global.asax ViewEngines.Engines.Add(new MyViewEngine());

Happy ending

I can use this in two ways: embedded in a view using Render.Partial or just returning PartialView from my controller.

Let me know if it helps you. And also you can share your solution.

We have a project coming down the line that's likely going to be in ASP.NET of some sort. I really hope this means ASP.NET MVC :)

I've created a SOAP web service and a small website in ASP.NET (non-MVC) before, so I'm familiar with the bare basics of C#, ASP.NET, and LINQ (except templates still confuse me significantly).

I am however a rather advanced Python programmer, and I've had a ton of experience in Django and Pylons. What's the best way to translate this knowledge to ASP.NET?

I'm especially interested in anything that involves the latest versions of .NET, and in best practices for .NET, Visual Studio, etc.

Knowing Django will put you in a good position to use ASP.NET MVC - you'll already know about the roles of Models and Views etc.

Python is generally a higher level language than C# so you might find that it can be less powerful to use. On the whole I'd say there isn't much between them though.

The best advice I could give would be to read Pro ASP.NET MVC Framework (Steve Sanderson). This book goes beyond simply teaching the reader about the features of the framework but clearly demonstrates them in context and gives clear examples of what could be considered 'best practice' (subjective, but I largely agree with the techniques he advocates).

I'm actually going the inverse at the moment. I've been using ASP.NET MVC for a couple of years but am moving towards Django for some upcoming projects.

I am completely new in MVC. I want to create one sample application from which I can do insert,update and delete in one page and view all records in other page. For that I tried to create .cs class for userMST table. As we do in normal application, a class file should have private fields, getter and setter methods to set the fields, insert/update/delete/select methods. But when I tried to define private properties I saw that .net is not allowing me to define private properties not I can set string as the type of the property.

I can not actually understand how the application is created. I did some googling but examples are given which do all the operation from wizard and uses the in-built databse. Please explain me how to start with MVC and how can I build sample application??

Thanks in advance...

If you're just starting out I would highly recommend you checkout the following tutorials:

And after doing that buy a book or two:

I'm looking for any complex example (book, article, video training) of how can I combine these tools and create a shop application.

I started developing online shop using examples from A. Freeman, S. Sanderson book.

I like the way the shopping cart is implemented in this book. But recently I've read an amazing article which represents another stack & capabilities: signalr (+Web API) allows all clients to be notified about changes made on server!

Questions I'm especially interested in are:

  • what is the best way to implement shopping cart? Of course implementations may vary! I know that. I simply need an authoritative reference on this. There's no need to consider sophisticated registration, shipping details, e-payement service in my case. At least for now.
  • How do I deal with shopping cart and backbone views, models, routing? Haven't found much information on it.
  • Things I've previously made with backbone.js failed in IE 8. I haven't examined it thoroughly yet. Are these things compatible at all?
  • Have you developed any production sites using jquery mobile? Is it worth switching from zurb foundation/twitter bootstrap frameworks?

Need your consultancy.

I'm working through the SportsStore example from Pro ASP.NET MVC 3 Framework. At the beginning of chapter 8 i'm instructed to edit my ProductController class, adding the .Where line as follows:

    public ViewResult List(string category, int page = 1)
        ProductsListViewModel viewModel = new ProductsListViewModel
            Products = repository.Products
                .Where(p => category == null || p.Category == category)
                .OrderBy(p => p.ProductID)
                .Skip((page - 1) * PageSize)
            PagingInfo = new PagingInfo
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = repository.Products.Count()
            CurrentCategory = category
        return View(viewModel);

When I run the code i get the following error:

Exception Details: System.Data.SqlServerCe.SqlCeException: The specified argument
value for the function is not valid. [ Argument # = 1,Name of
function(if known) = isnull ]

on the foreach line in the following code block:

@model SportsStore.WebUI.Models.ProductsListViewModel

    ViewBag.Title = "Products";

@foreach (var p in Model.Products)
    Html.RenderPartial("ProductSummary", p);
<div class="pager">
    @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))

I've searched a good bit and found a lot of references to this StackOverflow post in multiple places, but changing the query to

.Where(p => category == null ? true : p.Category == category)

had no effect.

Some basic information:

  • This is an MVC3 project using the Razer view engine and C#.
  • All of the items in my SQL Compact 4.0 database have a category.
  • Commenting out the category == null bit makes the code run just fine.
  • The second version I gave above is what is in the downloadable source code from their site.

It does work without the null checking, but i'm worried that if I just move on i may run into issues later on. Does anyone have any ideas as to how I can fix it?

I think the problem is that the LINQ query is being deferred until it gets to the SQL server. My guess is that the SQL compact server has an issue with checking category == null.

Try using a non-deferred LINQ method before calling the Where method. Something like

Products = repository.Products.ToList()
    .Where(p => category == null || p.Category == category)
    .OrderBy(p => p.ProductID)
    .Skip((page - 1) * PageSize)

Controller uses HttpContext request object to get relevant information and passes it along to viewmodel.

string user = HttpContext.Request.Headers["abc"]

Question is how to pass the same information i.e. HttpContext to POCO model where i have to set some parameters. i can't user System.Web.MVC

    public class Test
        public string userA;
        public Test()
            userA = "Here I want to get the user from HttpContext and set it";

creating HTTPContextBase object using HTTPContext.Current throws error

"Request is not available in current context"

any help would be appreciated.thanks

While it is a very good idea not to bound your Controllers to the HttpContext (as scott.korin mentions) I've found that there's some times no way around it (like when testing Routes).

Here's the code that we use, that is based on Steve Sanderson's book "Pro ASP.NET MVC 3 Framework". Pay close attention to the CreateHttpContext method.

    private void TestRouteMatch(string url, string controller, string action, object routeProperties = null, string httpMethod = "GET")
        // Arrange
        RouteCollection routes = new RouteCollection();
        // Act - process the route
        RouteData result = routes.GetRouteData(CreateHttpContext(url, httpMethod));
        // Assert
        Assert.IsTrue(TestIncomingRouteResult(result, controller, action, routeProperties));

    private bool TestIncomingRouteResult(RouteData routeResult, string controller, string action, object propertySet = null)
        Func<object, object, bool> valCompare = (v1, v2) =>
            return StringComparer.InvariantCultureIgnoreCase.Compare(v1, v2) == 0;
        bool result = valCompare(routeResult.Values["controller"], controller)
        && valCompare(routeResult.Values["action"], action);
        if (propertySet != null)
            PropertyInfo[] propInfo = propertySet.GetType().GetProperties();
            foreach (PropertyInfo pi in propInfo)
                if (!(routeResult.Values.ContainsKey(pi.Name)
                && valCompare(routeResult.Values[pi.Name],
                pi.GetValue(propertySet, null))))
                    result = false;
        return result;

    private void TestRouteFail(string url)
        // Arrange
        RouteCollection routes = new RouteCollection();
        // Act - process the route
        RouteData result = routes.GetRouteData(CreateHttpContext(url));
        // Assert
        Assert.IsTrue(result == null || result.Route == null);

    private HttpContextBase CreateHttpContext(string targetUrl = null, string httpMethod = "GET")
        // create the mock request
        Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
        mockRequest.Setup(m => m.AppRelativeCurrentExecutionFilePath).Returns(targetUrl);
        mockRequest.Setup(m => m.HttpMethod).Returns(httpMethod);
        // create the mock response
        Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();
        mockResponse.Setup(m => m.ApplyAppPathModifier(
        It.IsAny<string>())).Returns<string>(s => s);
        // create the mock context, using the request and response
        Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
        mockContext.Setup(m => m.Request).Returns(mockRequest.Object);
        mockContext.Setup(m => m.Response).Returns(mockResponse.Object);
        // return the mocked context
        return mockContext.Object;

I am probably going about this completely wrong here, but that is partly what I am asking.

I am creating a blog using MVC3 and I am having some issues. My homepage currently lists each blog post with their corresponding comments and topics correctly. I want it to be limited to a number of posts, so here is my code in the HomeController.

public class HomeController : Controller
    private MyDB db = new MyDB();

    public ActionResult Index()
        var posts = (from p in db.Set<BlogPost>()
                     orderby p.DateCreated descending 
                     select new PostViewModel
                                    Title = p.Title,
                                    DateCreated = p.DateCreated,
                                    Content = p.Content,
                                    Topics = p.Topics,
                                    Comments = p.Comments,
                                    CommentCount = p.Comments.Count

        IEnumerable<Topic> topics = from t in db.Topics
                                    select t;

        var blog = new BlogViewModel
            Post = posts,
            Topics = topics.Select(t => new SelectListItem { 
                Value = Convert.ToString(,
                Text = t.Name

        return View(blog);

This works fine as I've said. I have the topics coming in separately because I want to eventually sort by those (which I also don't know where to start but that's another story).

My main problem is that I would like to have a "Next" and "Previous" button under the 5 selected posts, that when clicked, grab the next 5 or previous 5. I've been told to use...

@Html.ActionLink("Next >>", "ActionName", "Home", Custom arguement?)

type of solution where I write a custom method in my HomeController and grab the next or previous 5. Is this at all correct? I'd like to understand the best use scenario for something like this. I am completely new to MVC3, so I am not looking for shortcuts, and I feel like I maybe already have made a few.

Thanks for your help.

You could create your Controller like the example code below:

    public ViewResult List(string category, int page = 1) {

        ProductsListViewModel viewModel = new ProductsListViewModel {
            Products = repository.Products
                .Where(p => category == null ? true : p.Category == category)
                .OrderBy(p => p.ProductID)
                .Skip((page - 1) * PageSize)
            PagingInfo = new PagingInfo {
                CurrentPage = page,
                ItemsPerPage = PageSize, //4 for example
                TotalItems =  category == null ? 
                    repository.Products.Count() : 
                    repository.Products.Where(e => e.Category == category).Count()
            CurrentCategory = category
        return View(viewModel);

Inside your View, you put this custom HTML Helper:

<div class="pager">
   @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", 
    new {page = x, category = Model.CurrentCategory}))

Here is the code of the Helper:

public static class PagingHelpers {

    public static MvcHtmlString PageLinks(this HtmlHelper html,
                                          PagingInfo pagingInfo,
                                          Func<int, string> pageUrl) {

        StringBuilder result = new StringBuilder();
        for (int i = 1; i <= pagingInfo.TotalPages; i++) {
            TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
            tag.MergeAttribute("href", pageUrl(i));
            tag.InnerHtml = i.ToString();
            if (i == pagingInfo.CurrentPage)

        return MvcHtmlString.Create(result.ToString());

This example was taken from this book

I find myself now with an EF Code First DbContext and entity classes, which I would prefer to exclude from unit testing right now, as Code First is not a critical requirement, and I would not unit test DB First generated classes, but above that I have a repository library, which are all copy and paste copies of one template, and then some view modes and controllers.

I would now like to adopt a TDD approach for the way forward, and add unit tests for view models that are not pure (property only) DTO's, and my action methods. Am I going in the right direction, with the right coverage in mind? Then, how do I unit test actions? Some pointers to resources and tutorials would be nice.

Ideally, in a perfectly TDD environment you would have tests for absolutely everything in your code - but some may consider that dogmatic and you don't see a need to test your code-first-generated-database, so don't do it :) . You're the developer, do what you want.

I understand your feelings on the above, but if you want to develop in a true TDD style, you need to write a test before you code anything, then code to get the 'green light' on the test.

The basic workflow would be as follows (starting on anything you wanted to add to your app past your DBContext)

  1. Realize you need a new feature for your MVC application
  2. Write a test that fails (because there is no actual code at this point)
  3. Write the new feature you were wanting to add to your application
  4. Run your test, if the test passes, move on to 5, if it fails, edit the code and repeat 4
  5. Refactor as needed and re-run the test to ensure that everything passes

You will have a lot of tests, but you will have a very sound application as long as you are diligent about maintaining those tests.

Keep a few things in mind when using TDD with MVC (or likely any development architecture):

  • Run your tests frequently
  • Make sure your tests all pass after they've passed once in the past (sounds obvious, but some people are crazy)
  • Make sure you can run your tests easily and quickly, preferably one or two clicks and the tests are run. This will allow you to more easily run them frequently - this is what the tests are here for.
  • Stick to it, it is easy to get lazy and just say, "yeah, I know this part will work, no need to test it," but when you are looking at that code weeks/months/years from now and you are not as closely connected to it, you may carelessly change something and run your project's tests (since it was developed using a TDD process) and notice everything passes. But, since there wasn't a test for the part you changed, you have no evidence that the code is all working as planned. It sounds simple, but think of it as a forgotten 'broken window' that can lead to other problems.

As far as writing tests specifically for MVC actions, I highly recommend this tutorial from MSDN and this book: Pro ASP.NET MVC 3 Framework (which is an overall great resource for MVC3, including TDD for MVC3) by Freeman and Sanderson.

I have just started to learn ASP.NET MVC 3 form this book and I have a problem with example from it.

I always get this error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name 'Text' does not exist in the current context

Here is the code:

@Html.DropDownListFor(p => p.WillAttend, new[]
                                                new SelectListItem(), Text = "Yes I'll be there", Value = bool.TrueString,
                                                new SelectListItem(), Text = "No, I can't come", Value =  bool.FalseString

                                            }, "Chose option")

Anyone know how to solve this problem?

you forgot some {}:

@Html.DropDownListFor(p => p.WillAttend, new[]
                                                new SelectListItem(){ Text = "Yes I'll be there", Value = bool.TrueString},
                                                new SelectListItem(){ Text = "No, I can't come", Value =  bool.FalseString}

                                            }, "Chose option")

I have two separate classes derived from the same interface, but have different validation/data annotations assigned. The requirement is that the same data needs to be collected, but on one screen nothing is required (a save screen), but on the other there are some required fields (a submit/finalize screen.) I've made a PartialView that is to be used in two separate View, one for save, one for final submit.

I've tried using the parent Interface as the View's model, however my validators don't fire (as I expect, I'm guessing that because the Interface itself doesn't have any annotations, nothing will fire.) Is there a way to have the page dynamically choose one class or the other depending on which page I'm using instead of the Interface?

As a side-note, this is being done in MVC 3 with Razor.

Could you use one class? You can create a filter that allows you to manage the validation errors for an action. In your case you can add an attribute to the Save action and ignore the required errors, but the validations will run for the submit/finalize action. This example will discard all the errors.

public class DontValidateEmailAttribute : ActionFilterAttribute {

  public override void OnActionExecuting(ActionExecutingContext filterContext) {
    var modelState = filterContext.Controller.ViewData.ModelState; 
    var incomingValues = filterContext.Controller.ValueProvider;

    foreach (var key in modelState.Keys) 


I learnt this technique from Steve Sanderson's Pro ASP NET MVC 3. He uses the technique to validate a model that has required fields but the data entry is a multistep wizard. If the value has not been returned in the form post, he removes the errors for that property.

I'm a junior developer, who knows the basics already and have some experience as well, but when it comes to building a project from ground up I'm useless in terms of writing a good maintainable code. I know there are tons of design patterns for this purpose, and as well I'm aware of the MVC3. Now, do I need to read design patterns books to be become a good architect for or should I concentrate on MVC as it is the new and better design pattern ? I have this impression that design patterns and MVC stand separately since MVC is "forced" design pattern on it's own. I need to clarify this for myself and appreciate all the answers ! Thanks.

do I need to read design patterns books to be become a good architect for or should I concentrate on MVC as it is the new and better design pattern ?

Yes :) All kidding aside, since you say you are a junior developer, I would start by writing one or two MVC applications first (even if they will be throw away apps) so that you get to "feel the pain" that the patterns solve. Reading about patterns is a great complement to writing code but I would keep the focus (at least initially) on your coding skills.

There are a lot of things that you probably will need to learn, but take it slowly. Don't try all the patterns and tools at once. A great book to read about MVC is Steven Sanderson's Pro ASP.NET MVC 3 He includes a very good sample application that he builds little by little following good programming practices.

i am at a beginner level on Asp.MVC 3. If any one could suggest me on what things one should know in Asp.Net-MVC. i am about to give some interviews to get a job to have a clear idea on what recriuters ask and what should i must learn to get a job in MVC

please suggest me some topics..

any help would be appreciated...

As adviced, is good starting point. You should also check out the NerdDinner and MvcMusicStore live examples.

There're currently two active books about ASP.NET MVC 3 (Latest version). Both good to get in depth knowledge of every aspect in framework. In fact, reading at least one of them is required if you want to get professional in framework.

And the last point - read articles, blogs, etc. From SO tag description:

Latest announcements from Microsoft usually come from Scott Guthrie's blog. Other notable blogs relating to MVC include Phil Haack, Scott Hanselman, and Brad Wilson.