Pro ASP.NET MVC Framework

Steven Sanderson

Mentioned 42

Steven Sanderson has seen the ASP.NET MVC framework mature from the start, so his experience, combined with comprehensive coverage of all its features, including those in the official MVC development toolkit, offers the clearest understanding of how this exciting framework could improve your coding efficiency—and you'll gain invaluable awareness of security, deployment, and interoperability challenges. The ASP.NET MVC Framework is the evolution of Microsoft's ASP.NET web platform. It introduced a radical high–productivity programming model that promotes cleaner code architecture, test–driven development, and powerful extensibility, combined with all the benefits of ASP.NET 3.5. An integral benefit of this book is that the core Model–View–Controller architectural concepts are not simply explained or discussed in isolation, but 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# 3.0 language features and unit–testing best practices. By gaining this invaluable, practical experience, you can discover MVCs strengths and weaknesses for yourself—and put your best learned theory into practice.

More on

Mentioned in questions and answers.

Possible Duplicate:
MVC Learning Resources

I'd like to improve my understanding of MVC design pattern, as I'll be probably using it in the future (my job is mainly focused in developing .NET web applications).

Can I ask to this community to help me find a starting direction on this subject? Articles, white papers, code samples, theory... anything you found helpful!

Being new to ASP.NET MVC, I've been wondering about the signature of Controller methods. In all the examples I've seen, they always seem to return ActionResult, even if they actually return a ViewResult instance or similar.

Here's a commonly seen example:

public ActionResult Index()
    return this.View();

In such a case, wouldn't it make more sense to declare the method as public ViewResult Index(), and get stronger type support?

Experimentation indicates that this works, so it seems possible.

I do realize that there may be situations where the polymorphism is desired (e.g. if you want to redirect only in certain situations, but show a view in other situations), but if the method always returns a view, I'd find a ViewResult more desirable.

In terms of future compatibility, ActionResult obviously provides a more robust signature, but if one controls the entire code base, it's always possible to change a method's signature to a more general return type if that should become necessary in the future.

Are the any other considerations that I'm not aware of, or should I just go ahead and declare my controller methods with specific return types?

You can absolutely use specific return types, even though most examples on the web seems to return the ActionResult. The only time I would return the ActionResult class is when different paths of the action method returns different subtypes.

Steven Sanderson also recommends returning specific types in his book Pro ASP.NET MVC Framework. Take a look at the quote below:

"This action method specifically declares that it returns an instance of ViewResult. It would work just the same if instead the method return type was ActionResult (the base class for all action results). In fact, some ASP.NET MVC programmers declare all their action methods as returning a nonspecific ActionResult, even if they know for sure that it will always return one particular subclass. However, it's a well-established principle in object-oriented programming that methods should return the most specific type they can (as well as accepting the most general parameter types they can). Following this principle maximizes convenience and flexibility for code that calls your method, such as your unit tests."

After being frustrated in my attempts to learn the arcana that is ASP.NET, I decided to try ASP.NET MVC.

I have extensive experience with C# 2.0 doing just about everything (WinForms, Windows Services, remoting, ...) except ASP.NET . I've been writing PHP for even longer than I've been coding .NET. With all of this experience, I thought I was ready for ASP.NET MVC. I now see I'm learning the following simultaneously and having a bit of a hard time with it:

  • the MVC pattern in general
  • .NET 3.5.

I'm currently about 1/2 way through the NerdDinner free book chapter. I don't feel completely lost but I do get the feeling that I'm not catching on to as much as I'd like to (due to the fact that I'm learning 4 things at once -- sometimes it's not clear which skills are from which abstraction layer).

What prerequisite knowledge would you recommend for ASP.NET MVC? Any/all of those I listed above? Others? Or maybe I'm just slow and most people would be fine doing what I did.

I recommend getting a book on ASP.NET MVC and working through the examples in the book. Don't worry too much about the history of the MVC design pattern or it's 1979 roots at Xerox PARC. I wouldn't bother reading much more about the actual MVC pattern than this simple article from MSDN: Cutting Edge: ASP.NET Presentation Patterns

I recently finished Steve Sanderson's Pro ASP.NET MVC Framework and I can recommend it. It has a multiple chapter sample application that gets you started quickly with ASP.NET MVC and then 10 or so follow-up chapters that cover the relevant topics in depth (Controllers, Views, Security, etc). The book has a strong focus on unit testing and dependency injection and also covers basic object relational mapping with LINQ to SQL. There is also chapters that cover integrating jQuery with ASP.NET MVC and how you might utilize framework components (authorization, membership, roles, personalization, caching, etc) from traditional WebForms applications.

There are a number of positive reviews on Steve's Blog which is also a good source of additional ASP.NET information. has a couple of positive reviews on the book (I need to add mine when I get some free time). You can also preview some of the book over at Google Books.

Some of the other books that are available now or available shortly are:

Wrox: Beginning ASP.NET MVC 1.0 --- Both authors Keyvan Nayyeri and Simone Chiaretta are active ASP.NET MVC bloggers. There is a sample chapter on testing for download here. I've read that it should be available at the end of June 2009?

Manning: ASP.NET MVC in Action --- This book is by Ben Scheirman, Jeffrey Palermo and Jimmy Bogard. They all have interesting blogs that cover ASP.NET MVC related topics. If I heard correctly, this book should be out in August 2009. You can pre-order the book (MEAP = Manning Early Access Program) here and get access to the first 11 chapters (unedited or loosely edited I think). The CodeCampServer reference application that complements the book is pretty intense and covers using nHibernate (ORM), Castle Windsor (DI / IoC), DDD, unit, integration and regression testing.

Wrox: Professional ASP.NET MVC 1.0 --- This is the book that accompanies the NerdDinner sample application and reader that was made available a while back. It's authored by some pretty smart Microsoft guys: Rob Conery, Scott Guthrie, Scott Hanselmann and Phil Haaaaaaaaaaaaack who have the inside information on why certain decisions were made with the framework. Available now.

Packt: ASP.NET MVC 1.0 Quickly --- The author Maarten Balliauw has a pretty good blog that talks about various ASP.NET MVC issues including testing. Available now.

Sams: ASP.NET MVC Framework Unleashed --- Author Stephen Walther is responsible for a number of popular ASP.NET Unleashed books from the early 1.0 days of ASP.NET and now he is writing a book on ASP.NET MVC. You can check out his blog for sample content from the upcoming book and other ASP.NET MVC related posts. Amazon says this book will be available in July 2009.

Wrox: ASP.NET MVC Website Programming Problem Design Solution --- This appears to be a follow-up to the book Wrox: ASP.NET 2.0 Website Programming: Problem Design Solution and welcomes back author Marco Bellinaso and introduces two new authors to the project Nick Berardi and Al Katawazi. The sample application for the book is the Beerhouse CMS and is available for download on CodePlex. The book's website says that it will be released in June 2009.

Apart from what others have recomended I would suggest the following two books:

  • Spring in Action : It's not ASP.NET MVC, it's about Spring, but the foundations are similar and it's really well written.
  • Pro ASP.NET MVC 2 Framework : It explains the concepts in an easy to follow way, and it helps introduce DI into ASP.NET MVC.

Is there any way to get posted files (<input type="file" />) to take part in model binding in ASP.NET MVC without manually looking at the request context in a custom model binder, and without creating a separate action method which only takes a posted file as input?

I would have thought that this would work:

class MyModel {
  public HttpPostedFileBase MyFile { get; set; }
  public int? OtherProperty { get; set; }

<form enctype="multipart/form-data">
  <input type="file" name="MyFile" />
  <input type="text" name="OtherProperty" />

public ActionResult Create(MyModel myModel) { ... } 

But given the above scenario, MyFile isn't even part of the value provider values in the binding context. (OtherProperty is, of course.) But it works if I do this:

public ActionResult Create(HttpPostedFileBase postedFile, ...) { ... } 

So, why does no binding occur when the parameter is a model, and how can I make it work? I have no problem with using a custom model binder, but how can I do this in a custom model binder without looking at Request.Files["MyFile"]?

For consistency, clarity and testability, I'd like my code to provide automatic binding of all properties on a model, including those bound to posted files, without manually inspecting the request context. I am currently testing model binding using the approach Scott Hanselman wrote about.

Or am I going about this in the wrong way? How would you solve this? Or is this not possible by design due to the history of separation between Request.Form and Request.Files?

You don't need to register a custom binder, HttpPostedFileBase is registered by default in the framework:

public ActionResult Create(HttpPostedFileBase myFile)

It helps to read a book every once in awhile, instead of relying solely on blogs and web forums.

I have a unit test fixture in which I'm trying to test a ControllerAction on an ASP.NET MVC controller that's used for membership functions on a web app. I'm trying to mock the HttpContext for the tests. The ControllerAction under test actually sets properties on the HttpContext, such as Session values, Response.Cookies values, etc. This isn't all of the code, but here is a rough sample of the test that I'm trying to get to run:

public void ValidRegistrationDataSuccessfullyCreatesAndRegistersUser()
    var context = new Mock<HttpContextBase>() {DefaultValue = DefaultValue.Mock};
    var provider = new Mock<MembershipProvider>(new object[] {context.Object});
    var controller = new AccountController(context.Object, provider.Object);
    // This just sets up a local FormCollection object with valid user data 
    // in it to use to attempt the registration
    ActionResult result = controller.Register(_registrationData);
    Assert.IsInstanceOfType(typeof(ViewResult), result);
    // Here is where I'd like to attempt to do Assertions against properties 
    // of the HttpContext, like ensuring that a Session object called "User" 
    // exists, and new auth cookie exists on the Response.Cookies collection. 
    // So far I've been unable to successfully check the values of those properties.
    // I've been unsuccessful in getting those properties setup correctly on my 
    // mock object so that my ControllerAction can actually *set* their values, 
    // and that I can make assertions on them afterwards. The above code actually
    // generates a StackOverflowException (which I've reported) on the
    // context.SetupAllProperties() call. What am I doing wrong, or what do I need 
    // to do to be able to set and assert on those context properties?

Not sure what I'm doing wrong, but I'd love it if someone could point me in the right direction and show me how to setup this mock HttpContextBase object such that my controller can actually set values on its properties, and I can make assertions on those properties to ensure that my ControllerAction is doing what I need it to.

Am I approaching this the wrong way? I know that MVC Controllers have a ControllerContext that I can use to set values for Session, etc, but I can't figure out how something like that could be mocked without injecting it. Is there some way of doing that instead? (I also need to be able to pass the context in to my MembershipProvider too) Would that be a better approach?


I'm using a version of some code Steve Sanderson included in his Pro Asp.NET MVC book... and I'm currently having a moral dilemma whether it's okay to post the code here. How about I compromise with a highly stripped down version? ;)

So this can easily be reused, create a class similar to the one below that you will pass your controller. This will set up your mocks and set them to your controller's ControllerContext

public class ContextMocks
    public Moq.Mock<HttpContextBase> HttpContext { get; set; }
    public Moq.Mock<HttpRequestBase> Request { get; set; }
    public RouteData RouteData { get; set; }

    public ContextMocks(Controller controller)
        //define context objects
        HttpContext = new Moq.Mock<HttpContextBase>();
        HttpContext.Setup(x => x.Request).Returns(Request.Object);
        //you would setup Response, Session, etc similarly with either mocks or fakes

        //apply context to controller
        RequestContext rc = new RequestContext(HttpContext.Object, new RouteData());
        controller.ControllerContext = new ControllerContext(rc, controller);

And then in your test method you'd just create an instance of ContextMocks and pass in the controller object you're testing:

Public void test()
     var mocks = new ContextMocks(controller);
     var req = controller.Request; 
     //do some asserts on Request object

Seems very similar to Craig's examples, but this is with Moq v3. I have to give props to Steve Sanderson for this - I'm using this as a basis for testing all kinds of otherwise traditionally hard-to-test stuff: cookies, session, request method, querystring and more!

In ASP.NET MVC (default routing), I'd like to use a URL like this to return a View with a form to edit a customer:


I need to make use of CustomerId=5, but I don't want to permit a customer to change it. Right now I make the id hidden using:

This accomplishes what I want, but I'm under the impression that hidden form variables are not secure and can be manipulated by the end user.

So, what's the best way to allow a customer to edit their information but not their ID?

My solution was to use the Tamper Proofing code from Steven Sanderson's ASP.NET MVC book. The idea is that you create a hash of any hidden form field you want to tamper proof:

<%= Html.Hidden("CustomerId") %>
<%= Html.Hidden("CustomerIdHash") %>

When the form is submitted, Steven's code then computes another hash of CustomerId and makes certain it equals CustomerIdHash. If it does, then no tampering has occurred. It's great code, and worth the price of the book.

I using this Ajax.BeginForm

    <% using( Ajax.BeginForm( "Create","Mandate",
                       new AjaxOptions( ) {
                           OnSuccess = "GoToMandates",
                           OnFailure = "ShowPopUpError"
                       } ) ) {%>

<% } %>

What do I need to write in the controler to catch this OnSucces and OnFailure.

Because OnSuccess I need to show Success message

OnFailure I need to show othere message.

In my Controller

Public ActionResult GetSomething(FromCollection collection)
     if(exists == null)

Can anydboy help me out.. how to catch this?


The OnSuccess and OnFailure looks like they are expecting javascript callback functions.

<script type="text/javascript">
    function handleError(ajaxContext) {
    var response = ajaxContext.get_response();
    var statusCode = response.get_statusCode();
    alert("Sorry, the request failed with status code " + statusCode);

<%= Ajax.ActionLink("Click me", "MyAction",
new AjaxOptions { UpdateTargetId = "myElement", OnFailure = "handleError"}) %>

Example from Pro ASP.NET Framework page 425

ASP.NET AjaxOptions Class

Added Controller Example

The simpliest way to do this would be what I've got here but I recommend looking into strongly typed mvc views using some kind of ViewModel and maybe look into using jQuery for your ajax. With that said this should hopefully work for you.

if (exists)
  ViewData["msg"] = "Some Success Message";
  ViewData["msg"] = "Some Error Message";

return View();

In your view

<div id="myResults" style="border: 2px dotted red; padding: .5em;">
    <%: ViewData["msg"]%>

Do you find that when you work with a new technology that you're never quite sure what security gaps your leaving in your code?

I've been working with ASP.Net Web Forms for about 5 years now and am fairly confident my code is at least secure enough to stop most known attacks. Looking back a lot of my early code I have unknowingly left gaps in a lot of the security areas especially query strings and viewstate but I feel over time I learnt what the vulnerabilities were and made sure I didn't make the same mistakes again.

However I've recently started a new project in ASP.Net MVC and I really have no idea what security holes I'm leaving open. This reason alone is almost putting me off going forth with this. I'm reading up on it like crazy at the minute but am sure I've not learnt nearly enough to make it as secure as I could with Web Forms. What do you guys do to make sure you don't leave yourself open to attack?

Edit : Starting Bounty as Curious to see if there are any more opinions

I think a LOT of what you learned about with ASP.NET is transferable to ASP.NET MVC. It's still HTML (exploits: XSS) over HTTP (exploits: all input [cookies, URL parameters, form input, headers] can be forged, session hijacking, CSRF) with a database back end (exploits: SQL injection).

I would recommend Steve Sanderson's book on ASP.NET MVC titled Pro ASP.NET MVC Framework. It has an entire chapter dedicated to these topics.

Check out Chapter 13 'Security and Vulnerability' from the Table of Contents for the book.

Now I've seen some questions like this, but it's not exactly what I want to ask, so for all those screaming duplicate, I apologize :).

I've barely touched ASP.NET MVC but from what I understand there is no ViewState/ControlState... fine. So my question is what is the alternative to retaining a control's state? Do we go back to old school ASP where we might simulate what ASP.NET ViewState/ControlState does by creating hidden form inputs with the control's state, or with MVC, do we just assume AJAX always and retain all state client-side and make AJAX calls to update?

This question has some answers, Maintaining viewstate in mvc?, but not exactly what I'm looking for in an answer.

UPDATE: Thanks for all the answers so far. Just to clear up what I'm not looking for and what I'm looking for:

Not looking for:

  • Session solution
  • Cookie solution
  • Not looking to mimic WebForms in MVC

What I am/was looking for:

  • A method that only retains the state on postback if data is not rebound to a control. Think WebForms with the scenario of only binding a grid on the initial page load, i.e. only rebinding the data when necessary. As I mentioned, I'm not trying to mimic WebForms, just wondering what mechanisms MVC offers.

The convention is already available without jumping through too many hoops. The trick is to wire up the TextBox values based off of the model you pass into the view.

public ActionResult CreatePost()
  return View();

public ActionResult CreatePost(FormCollection formCollection)
    // do your logic here

    // maybe u want to stop and return the form
    return View(formCollection);
    // this will pass the collection back to the ViewEngine
    return View(formCollection);

What happens next is the ViewEngine takes the formCollection and matches the keys within the collection with the ID names/values you have in your view, using the Html helpers. For example:

<div id="content">

  <% using (Html.BeginForm()) { %>

  Enter the Post Title: <%= Html.TextBox("Title", Model["Title"], 50) %><br />
  Enter the Post Body: <%= Html.TextArea("Body", Model["Body"]) %><br />

  <%= Html.SubmitButton() %>

  <% } %>


Notice the textbox and textarea has the IDs of Title and Body? Now, notice how I am setting the values from the View's Model object? Since you passed in a FormCollection (and you should set the view to be strongly typed with a FormCollection), you can now access it. Or, without strongly-typing, you can simply use ViewData["Title"] (I think).

POOF Your magical ViewState. This concept is called convention over configuration.

Now, the above code is in its simplest, rawest form using FormCollection. Things get interesting when you start using ViewModels, instead of the FormCollection. You can start to add your own validation of your Models/ViewModels and have the controller bubble up the custom validation errors automatically. That's an answer for another day though.

I would suggest using a PostFormViewModel instead of the Post object, but to each-his-own. Either way, by requiring an object on the action method, you now get an IsValid() method you can call.

public ActionResult CreatePost(Post post)

  // errors should already be in the collection here
  if (false == ModelState.IsValid())
    return View(post);

    // do your logic here

    // maybe u want to stop and return the form
    return View(post);
    // this will pass the collection back to the ViewEngine
    return View(post);

And your Strongly-Typed view would need to be tweaked:

<div id="content">

  <% using (Html.BeginForm()) { %>

  Enter the Post Title: <%= Html.TextBox("Title", Model.Title, 50) %><br />
  Enter the Post Body: <%= Html.TextArea("Body", Model.Body) %><br />

  <%= Html.SubmitButton() %>

  <% } %>


You can take it a step further and display the errors as well in the view, directly from the ModelState that you set in the controller.

<div id="content">

  <%= Html.ValidationSummary() %>

  <% using (Html.BeginForm()) { %>

  Enter the Post Title: 
    <%= Html.TextBox("Title", Model.Title, 50) %>
    <%= Html.ValidationMessage("Title") %><br />

  Enter the Post Body: 
    <%= Html.TextArea("Body", Model.Body) %>
    <%= Html.ValidationMessage("Body") %><br />

  <%= Html.SubmitButton() %>

  <% } %>


What is interesting with this approach is that you will notice I am not setting the validation summary, nor the individual validation messages in the View. I like to practice DDD concepts, which means my validation messages (and summaries) are controlled in my domain and get passed up in the form of a collection. Then, I loop throught he collection (if any errors exist) and add them to the current ModelState.AddErrors collection. The rest is automatic when you return View(post).

Lots of lots of convention is out. A few books I highly recommend that cover these patterns in much more detail are:

And in that order the first covers the raw nuts and bolts of the entire MVC framework. The latter covers advanced techniques outside of the Microsoft official relm, with several external tools to make your life much easier (Castle Windsor, Moq, etc).

I was looking into additional ways to test ASP.NET MVC applications and ran into Steve Sanderson’s MvcIntegrationTestFramework. The approach looks rather promising but I was wondering if anyone had any actual experience to share.

I haven't used this framework. But based on my experience of reading his book -Pro ASP.NET MVC Framework, and another validation framework xVal he developed, I would say "HE IS GREAT".

I am trying to learn MVC in detail, and I am wondering whats the exact functional flow internally, in the sense of which functions(important functions) are called and what they does when the application starts and which function are called apart from the controller actions that we write in our application as we proceed.

Help in this regard will be much appreciated. Please do suggest some good resources as well if you found any in this regard.


Check out Redgates's free "The ASP.NET MVC Request Handling Pipeline" poster for execution flow

and Steven Sanderson's MCV book for details.

I am using Castle Windsor to manage controller instances (among other things). My controller factory looks like this:

public class WindsorControllerFactory : DefaultControllerFactory
        private WindsorContainer _container;

        public WindsorControllerFactory()
            _container = new WindsorContainer(new XmlInterpreter());

            var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
                                  where typeof(Controller).IsAssignableFrom(t)
                                  select t;

            foreach (Type t in controllerTypes)
                _container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient);

        protected override IController GetControllerInstance(Type controllerType)
            return (IController)_container.Resolve(controllerType); // ArgumentNullException is thrown here

When I start up my ASP.Net MVC application and try to go to "/" (or another path), I get an ArgumentNullException. I put a break point on entry of the GetControllerInstance and found that it's called once with my HomeController, then a second time with null (which is when the exception is thrown). Why is it being called again?

Should I change the method to something like this:

protected override IController GetControllerInstance(Type controllerType)
    if (controllerType == null)
        return null;

    return (IController)_container.Resolve(controllerType);

Had this problem when following the Pro ASP.NET MVC Framework book, added


to the routes in the global.asax.cs file and it works. See more here: serving favicon.

I need recommendations on a good Unit Testing book for use with ASP.NET MVC. Based on books you have actually read and use (your bible), what do you recommend?

I like Kent Beck's "Test Driven Development: By Example" (amazon link) as an introduction to TDD, it's not specific to C# nor ASP.NET MVC.

It seems that all of the newer ASP.NET MVC books have at least one chapter on unit testing.

I have recently completed Steve Sanderson's book Pro ASP.NET MVC Framework and I thought the author placed a strong emphasis on unit testing. The book doesn't have a dedicated chapter on unit testing, but just about every chapter has relevant sections or call-outs/sidebars that deal with testing routing (inbound and outbound), controllers, repositories, model binders, etc. If I remember he uses the nUnit and Moq libraries in great detail. You can preview parts of his book on Google Books : Pro ASP.NET MVC Framework or order it from Apress (their eBooks are reasonably priced but password protected with your email address which is sort of a pain for me) or from Amazon.

I haven't seen any plans for a book solely on ASP.NET MVC unit testing, so you're going to probably have to stick to blogs or with whatever content you can find in the upcoming ASP.NET MVC books (like I said, it seems that all of them cover unit testing to varying degrees).

Some of the books that I know of:

Wrox: Beginning ASP.NET MVC 1.0 --- Has a sample chapter on testing for download here.

Manning: ASP.NET MVC in Action --- Doesn't have an explicit chapter on testing, but if you download the CodeCampServer reference application you will find a ton of unit, integration, and regression tests.

Wrox: Professional ASP.NET MVC 1.0 --- Has unit tests in the NerdDinner sample application and a dedicated chapter on testing. Testing Guru Roy Osherove (author of The Art of Unit Testing) reviews the NerdDinner tests here.

Packt: ASP.NET MVC 1.0 Quickly --- Has a chapter on unit testing and the author has a pretty good blog that talks about various ASP.NET MVC issues including testing.

Sams: ASP.NET MVC Framework Unleashed --- Browsing the Table of Contents for the book reveals a fair amount of content dedicated to testing (mocking, TDD, etc). You can check out the author's blog for sample content from the upcoming book and other ASP.NET MVC and TDD related posts.

Are there any clear guidelines and best practices on using JQuery and ASP.NET MVC together? articles, blog posts, books? not just MVC, but on the connection between them and known good ways and patterns of making them work together.

Roy - You ask a good question.

In my experience, the best resource that addresses your question is Chapter 12 of Steven Sanderson's Pro ASP.NET MVC Framework book.

I'm eager to see others respond to this question too.

I'm done some WinForms work in C# but now moving to have to develop a web application front end in .NET (C#). I have experience developing web apps in Ruby on Rails (& a little with Java with JSP pages & struts mvc).

Should I jump straight to MVC framework? (as opposed to going That is from the point of view of future direction for Microsoft & as well ease in ramping up from myself.

Or if you like, given my experience to date, what would the pros/cons for me re MVC versus


I used to work on desktop applications too, and never really got into web stuff. I didnt even (gasp!) knew HTML (yeah, that was my programmers shame). In my new job we were going to start a new application using ASP.NET MVC and I gotta tell you, I love it. HOWEVER I think you should only go with MVC if you are or you count with someone with good html/css design skills.

Html is easy I know (I've learned it know!) but I think its kind of hard to make nice designs with html and css, specially if you suck at designing and you could probably do prettier stuff using webforms, which is a little bit easier/similar to winforms.

Also, if you go the MVC way make sure you have enough time to learn it, since you are going to go a little bit more low level, gonna have to learn more of the little details, like the actual difference between post/get and all that stuff that is pretty much completely hidden in webforms. I would really recommend getting a book, I used this one Pro MVC and really liked it.

Finally, if your page is gonna have interactive bits, or ajax-y things, if you go the MVC way you are more likely gonna have to learn javascript/jQuery too. If you go the webforms you can use the included drag'n drop ajax controls.

My question is straight forward. I'm totally new to the Microsoft stack, I have experience in web programming using PHP and Django; and I'm very interested in learning ASP.NET MVC. Is there a way (tutorials, reference books.. what ever!) to learn the C# language AND ASP.NET MVC at the same time? I mean in the same introductory material (same book, same tutorial, same -your suggestion-? Time is an issue for me.

Thanks in advance ;-)

If you are completely new to .NET and C# I would recommend you Head First C#. For ASP.NET MVC there's ASP.NET MVC in Action. More advanced is Pro ASP.NET MVC Framework.

DataAnnotations vs IDataErrorInfo

Pros and Cons of both? Benefits of one over the other? (especially related to MVC)

Late entry to the discussion as I do not want to start a new question. Where I am coming from is to determine the best practice to apply to a medium size ASP.NET MVC project.

Let me first summarise our options :-

1) IDataErrorInfo is simple to implement. All you need is to derive IDataErrorInfo in your Model class. The catch is that you are letting your model binding to be enforcing your business rules. Business rules should be enforced by the Model. The other catch for IDataErrorInfo (and likewise for DataAnnotations) is that (paraphrasing from Steven Sanderson's book it could not report multiple errors relating to a single property or multiple errors relating to the whle object model.

2) DataAnnotation to me, is like a schema check (validation). This is the first check that your application should do. However (IMHO), it is not suited to implement your business rules.

3) Implement your own ModelBinder. Although this can be done but seriously speaking, the usage of ModelBinder is to parse and bind your data to your model and not to perform complicated validations and business rule checks. I would leave the Business rules check to be implemented in your Model/Domain layer.

4) Roll your own - Validating with a service layer (see this. The example shown has its advantage of decoupling from the Controller and Model State using an interface class. Another option is to throw an appropriate exception from your model layer. The latter option is useful when you implement your service layer in a separate application (e.g a WCF application).

What do you think? For a medium to large size project, which of the above options have you used (or intend to adopt) and why?


I am coming from a PHP background and I am familiar with OOP concepts, but I am moving away from PHP and trying out ASP.NET MVC using C#.

Even without being forced to use web forms, this is a big jump for me coming from PHP. This is worsened by the fact that there are not very many tutorials out there on this subject in comparison to PHP.

All the tutorials I have found online are too complex or not very well put together so when I am going through them I always miss something that adds much confusion. That being said I understand the Visual Studio IDE pretty well from past experiences.

Is there any decent and simple MCV tutorial out there on the web that would be decent for a PHP programmer?

I have been working with ASP.NET MVC since it Beta days and have always found lack of proper technical details in blogs and forum posts to be quite inhibiting in the climbing up the learning curve. Then, ScottGu, ScottHa and others posted the Nerddiner sample application and the first chapter of the excellent Professional ASP.NET MVC 1.0 book.

It is a good idea to look at sample code/applications and build our own blog/forum application using ASP.NET MVC while working your way through. Steven Sanderson's book and his blog are terrific resources too.

HTH, indyfromoz

As I am new to mvc I would like to get the list of developers or software experts who use or developed mvc ... It would be very useful for budding developers like me to know about their articles and ideas towards devlopement...

I know a few

I want some more authors and their blogs because it would be very helpful to see what they faced during their developement

Scott Hanselman wrote Professional ASP.Net MVC 1.0 with Phil Haack, Rob Conery and Scott Guthrie. He blogs at and podcasts at

Steve Sanderson. He wrote the xVal project as well as what I consider the definitive ASP.NET MVC book Pro ASP.NET MVC

Just wondering why almost every controller method I see in sample MVC code returns ActionResult, even if it's obvious that the code can only return one type of result. I understand there are certain instances where it's warranted because you may return, say a RedirectResult or a ViewResult depending on the logic, but that's not the case for most of the methods I've seen.

Isn't it tantamount to having a return type of 'object' on a method? Why not just specify JsonResult, or FileResult or ViewResult as the return type? Is there a benefit I'm not seeing to settting the return type to ActionResult on every controller method?

Classic example:

public ActionResult Index()
    return View();

Why does this seem to be the norm instead of this:

public ViewResult Index()
    return View();

EDIT: So far all of the responses except for one have indicated that ActionResult is just more generic. I know that much. :) Why is this accepted practice on a controller method though, and not anywhere else? You don't just return the highest level-base classes of a type that you can on a normal method, you attempt to return the most specific type you can usually. What makes controller methods so different that bloggers and "sample code writers" (yes, I made that term up) would just resort to returning ActionResult?

quoted varbatim from an accepted answer here on SO. makes sense to me:

Must ASP.NET MVC Controller Methods Return ActionResult?

You can absolutely use specific return types, even though most examples on the web seems to return the ActionResult. The only time I would return the ActionResult class is when different paths of the action method returns different subtypes.

Steven Sanderson also recommends returning specific types in his book Pro ASP.NET MVC Framework. Take a look at the quote below:

"This action method specifically declares that it returns an instance of ViewResult. It would work just the same if instead the method return type was ActionResult (the base class for all action results). In fact, some ASP.NET MVC programmers declare all their action methods as returning a nonspecific ActionResult, even if they know for sure that it will always return one particular subclass. However, it's a well-established principle in object-oriented programming that methods should return the most specific type they can (as well as accepting the most general parameter types they can). Following this principle maximizes convenience and flexibility for code that calls your method, such as your unit tests."

see also:

I recently began reading Pro ASP.NET MVC Framework.

The author talks about creating repositories, and using interfaces to set up quick automated tests, which sounds awesome.

But it carries the problem of having to declare yourself all the fields for each table in the database twice: once in the actual database, and once in the C# code, instead of auto-generating the C# data access classes with an ORM.

I do understand that this is a great practice, and enables TDD which also looks awesome. But my question is:

Isn't there any workaround having to declare fields twice: both in the database and the C# code? Can't I use something that auto-generates the C# code but still allows me to do TDD without having to manually create all the business logic in C# and creating a repository (and a fake one too) for each table?

If you use Entity Framework 4, you can generate POCO object automatically from the database. (

Then you can implement a generic IRepository and its generic SqlRepository, this will allow you to have a repository for all your objects. This is explained here :

This is a clean way to achieve what you want: you only declare your object once in your database, generate them automatically, and can easily access them with your repository (in addition you can do IoC and unit test :) )

I recommend you to read the second edition of this book which is pure gold and updated with the new features introduced in MVC 2

And you should also read about the new features introduced in MVC3 which is now in RC (there is a new view engine really useful)

Can somebody give me a link to article or name of book, where i can find something about Design Patterns in ASP .NET MVC applications? Sry if i asking for something stupid, i'm not expert in this.

MVC itself is a design pattern. You can use several combinations of other design patterns in your application to suit your particular needs.

If you want a read an excellent book on ASP.NET MVC then I would recommend Steven Sanderson's book -

Note: This book is available for MVC2 as well, but I have not read that one. This book uses several good concepts that will help you create a production ASP.NET MVC application including TDD, repository pattern etc

I'd recommend Steven Sanderson's book for how to use MVC (probably worth waiting for the MVC 3 version which is due soon)

Otherwise I'd look at general design patterns books like Head First Design Patterns as these still apply within MVC.

Do you have a more specific question around a particular design pattern?

Best resources & books for ASP.NET MVC Framework

I started reading Pro ASP.NET MVC Framework by Steven Sanderson and so far it's excellent. Also, reviews on Amazon are very positive.

I have a grid with contact information which I need to be able to page through.

All the plumbing is already in place, with one last detail. Paging is done through a simple p Querystring parameter, e.g. would be the third page; the repository is automatically fetching the right data, and also the total count of items. The size of each page is defined somewhere else and I don't need to worry about that in the query string.

However, I support searching etc. as well. The search term searched for in denoted as q in my Querystring. So now I can have a combination: which searches for "tom" and pulls the second page of results.

The problem I face now, since the q (or other) parameters may be present in the query string, how do I create a pager for this (which would need to keep the original parameters, so if I click on "page 2" it needs to go from




How can I do this?

I asked a similar question yesterday. Maybe you want to check out Preserve data in .net mvc

following is the code copied from Steve Sanderson's book

public static class PagingHelpers
    public static string PageLinks(this HtmlHelper html, int currentPage,
    int totalPages, Func<int, string> pageUrl)
        StringBuilder result = new StringBuilder();
        for (int i = 1; i <= totalPages; i++)
            TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag

            tag.MergeAttribute("href", pageUrl(i));
            tag.InnerHtml = i.ToString();
            if (i == currentPage)

        return result.ToString();

I have created an ASP.NET MVC application and am trying to use Castle Windsor as my IOC

However, when the controllers are trying to resolve I am getting 'Content' and 'Scripts' into the 'controllerName' parameter in the CreateController(RequestContext requestContext, string controllerName) method. Needless to say these are not controllers. They appears to be the folders of the web site

Why is it trying to register these as controllers?

How do I ignore these folders??


exception from WindsorControllerFactory

Due to not being able to post the image I have to describe it - it basically just says

'The contentcontroller was not found'


public static IIocContainer Ioc;

            protected void Application_Start()

private void InitialiseIocContainer()
            IWindsorContainer _container = new WindsorContainer();

            var controllerTypes = typeof (GidgetController).Assembly.GetTypes();
            foreach (var controllerType in controllerTypes.Where((t=>typeof(IController).IsAssignableFrom(t))))
                _container.AddComponentLifeStyle(controllerType.Name.ToLower(), controllerType, LifestyleType.Transient);   

            _container.AddComponent("a",typeof(IGidgetService), typeof(GidgetService));
            _container.AddComponent("b",typeof(IGidgetRepository), typeof(GidgetRepository));
            _container.AddComponent("c",typeof(IGidgetValidator), typeof(GidgetValidator));

            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container));



public IController CreateController(RequestContext requestContext, string controllerName)
                controllerName = controllerName.ToLower() + "controller";
                var controller = _container.Resolve<IController>(controllerName);
                return controller;
            catch (ComponentNotFoundException)
                throw new HttpException(404, string.Format("The {0} controller was not found", controllerName));



I follow Steve Sanderson's pattern in creating a WindsorControllerFactory, which works quite well. I've modified his to actually return proper 404s when there isn't a controller by the name (i.e. someone types "/garbageblahblah") because his pattern didn't pick it up. So, I use Reflector to grab the bits that are built into the default controller factory for handling bad urls.

His pattern uses reflection to find all controllers within your Mvc project, and register them all upon app startup. You don't want to use CreateController, but instead GetControllerInstance() as this is only called by the underlying Mvc framework when a controller is going to be invoked. /Content is ignored by convention, and therefore is not called.

My CastleWindsorControllerFactory:

/// <summary>
/// Represents a special controller factory.
/// </summary>
public class CastleWindsorControllerFactory : DefaultControllerFactory
    WindsorContainer _container;

    public CastleWindsorControllerFactory()
        // register all controllers from the calling assembly.
        // (e.g. the mvc site calling this factory)
        _container =
            new WindsorContainer(
                new XmlInterpreter(
                    new ConfigResource("castle")

        // change this to Assembly.GetAssembly() if used directly from
        // your MVC website.  The code below is for when this class
        // exists in a seperate assembly.
        var controllers =
            from t in Assembly.GetCallingAssembly().GetTypes()
            where typeof(IController).IsAssignableFrom(t)
            select t;

        foreach (Type t in controllers)
                t.FullName, t, LifestyleType.Transient); 

    protected override IController GetControllerInstance(Type controllerType)
        if (controllerType == null)
            throw new HttpException(
                , string.Format(
                    , "Controller Not Found"
                    , new object[] {
                        this.RequestContext.HttpContext.Request.Path }));
        if (false == typeof(IController).IsAssignableFrom(controllerType))
            throw new ArgumentException(
                    , "Type does not sub-class the controller base"
                    , new object[] { controllerType }), "controllerType");

            (IController) _container.Resolve(controllerType);

And within my Globals.asax.cs, this is all you need (what you have above is vast overkill! I already loop through and register them within my CastleWindsorControllerFactor above).

protected void Application_Start()

    // custom controller factory that uses Windsor
        new CastleWindsorControllerFactory());

    // Uncomment to debug routes

Technically, this isn't exactly the code I use. I have actually abstracted the entire Castle Windsor off to a static instance in a class I call ComponentFactory. This allows me to have true Singleton patterns through my applications, amongst several strong-type additions.

I mention this, because I plan on releasing ComponentFactory() soon on my blog. But, drop me an email and I'll send the latest version to you. Email is: me -at-

I'm in a hoo-ha with my boss as I can't shift to using newer technologies until I have proof of some outstanding issues. One of the main concerns is how repositories deal with connections. One of the supposedly largest overheads is connecting and disconnecting to/from the database. If I have a repository where I do the following:

public ContractsControlRepository()
  : base(ConfigurationManager.ConnectionStrings["AccountsConnectionString"].ToString()) { }

with the class like so:

public class ContractsControlRepository : DataContext, IContractsControlRepository

with functions like:

public IEnumerable<COContractCostCentre> ListContractCostCentres(int contractID)
    string query = "SELECT C.ContractID, C.CCCode, MAC.CostCentre, C.Percentage FROM tblCC_Contract_CC C JOIN tblMA_CostCentre MAC ON MAC.CCCode = C.CCCode WHERE C.ContractID = {0}";
    return this.ExecuteQuery<COContractCostCentre>(query, contractID);

Now if in my controller action called _contractsControlRepository.ListContractCostCentres(2) followed immediately by another call to the repository, does it use the same connection? When does the connection open in the controller? When is it closed?



I'm using hand-written LINQ as suggested by Steve Sanderson in his ASP.NET MVC book.


To clarify, I'm using LINQ as my ORM, but I'm using raw SQL queries (as shown in the extract above) for querying. For example, here's a controller action:

public ActionResult EditBusiness(string id)
   Business business = _contractsControlRepository.FetchBusinessByID(id);
   return View(business);

I'm not opening/closing connections.

Here's a larger, more complete extract of my repo:

public class ContractsControlRepository : DataContext, IContractsControlRepository
    public ContractsControlRepository()
      : base(ConfigurationManager.ConnectionStrings["AccountsConnectionString"].ToString()) { }

public IEnumerable<COContractCostCentre> ListContractCostCentres(int contractID)
  string query = "SELECT C.ContractID, C.CCCode, MAC.CostCentre, C.Percentage FROM tblCC_Contract_CC C JOIN tblMA_CostCentre MAC ON MAC.CCCode = C.CCCode WHERE C.ContractID = {0}";
  return this.ExecuteQuery<COContractCostCentre>(query, contractID);

Then ContractsControlRepository is instantiated in my controller and used like _contractsControlRepository.ListContractCostCentres(2). Connections aren't opened manually, DataContext deals with that for me.

Without knowing the details of your ORM and how it connects the SQL database drivers will connection pool. When a connection is closed it is released back to the pool and kept open for X number of seconds (where X is configurable). If another connection is opened and all the parameters match (the server name, the application name, the database name, the authentication details etc.) then any free, but open connections in the pool will get reused instead of opening a brand new connection.

Having not read the book in question I don't know what "manual linq" actually is. If it's manual means you're getting the tables back youself then obviously you're doing the connection open/close. Linq to SQL will use a new connection object when a statement is finally executed at which point connection pooling comes into play - which means a new connection object may not be an actual new connection.

Our ad department pumps out Html code that they constantly change (and totally manage themselves). They have no knowledge of JavaScript, let alone C# etc. beyond a purely designer's point of view. Anything in their realm will be purely HTML and CSS (just like InDesign is to PostScript printing). All of this is really as it should be (truly separated concerns).

So, within MS MVC views, it looks like the norm is to lace html with C# code using <%= %>. Of course, if I do this, it will be removed next update. With JavaScript, we simply locate what we need with JQuery then add the appropriate code.

One very important thought as Phil Haack noted somewhere in his blog (forgive me if I state this incorrectly) is to include what data you need on the first visit within the first visit's html. (Again I apologize if I state this incorrectly) this is because heavy traffic websites cause a delay when loading the data separately which is not desirable.

So is there a way to pseudo separate your html markup from the C# code on the server rather than load data separately with JQuery client side? I can have them break up the HTML as necessary, like we do with partial pages. I can even have them add placeholders with HTML tags as necessary since this is more XML than programming, e.g.,
<productName> Apple </productName>

Any ideas?

Yes, there is. Use the HtmlHelper's RenderAction extension and move that logic back into a controller action, where it belongs. I blogged about it here:

Basically, RenderAction is similar to RenderPartial - except it actually calls an Action method on a Controller. THis allows you to call a controller's action method from your View, and pass any parameters (such as the Model, Route, etc) into the action method to write code against. It has greatly simplified our views by moving that logic back into the controllers, and using additional partial views loaded by those smaller action method calls.

RenderAction was suppose to be part of Asp.Net Mvc 1.0, but it didn't make the cut before RC1. Microsoft has said it will be included in Asp.Net Mvc when it is released.

Steven Sanderson also write a book that included extensive use of RenderAction in Pro Asp.Net Mvc Framework.

The following line on page 110 of Pro ASP.NET MVC Framework does not make sense to me:

string links = ((HtmlHelper)null).PageLinks(2, 3, i => "Page" + i);

I don't understand what is the null doing in the above statement?

I was unable to do .. HtmlHelper.PageLinks(....)

Is the PageLinks Method an extension method?

It's invoking an extension method on a null "instance" of an HtmlHelper. Probably there's no HtmlHelper in scope and the author can't be bothered to create one. The PageLinks method itself will not require a reference to an HtmlHelper, so effectively the author is passing null.

If you think about the signature of the extension method:

public static string PageLinks
    (this HtmlHelper helper, int val1, int val2, Func<someType,string> func)

It simply means that the parameter helper will be passed as null. It's a weird construct though, particularly in a book. It's got a really hacky smell to it.

The call could be restated (perhaps more clearly) as:

AuthorsHtmlExtensionsClass.PageLinks(null, 2, 3, i => "Page" + i)

Just reading though my MVC2 copy of the same book, (it's the end of the SportsStore application, right?), Steven has changed the code to:

HtmlHelper html=null;

Which I suppose is a little clearer.

After reading the first 7 chapters of Pro ASP.NET MVC Framework -a very recommended read, i'd say. Throughout my reading, the author -Steve Sanderson, touched on some TDD practices a lot. Now my question is:
Steve used to perform his unit tests against the controllers themselves, an example of the book:

    public void List_Includes_All_Products_When_Category_IsNull() {
        IProductsRepository repository = MockProductsRepository(
            new Product { Name = "First Product", Category= "Cat11"}, 
            new Product { Name = "SecondProduct", Category = "Cat22" } 
        ProductsController controller = new ProductsController(repository);
        controller.PageSize = 10;

        var result = controller.List(null, 1);

        Assert.IsNotNull(result, "Didn't render view!");
        var model = controller.ViewData.Model as IList<Product>;
        Assert.AreEqual(2, model.Count, "Got wrong number of products!");
        Assert.AreEqual(model[0].Name, "First Product", "Not the expected first item.");
        Assert.AreEqual(model[1].Name, "SecondProduct", "Not the expected second item.");           

I understand why Steve is testing this, obviously he needs to check his logic against the ViewData flags he set, that's why he needs to call the List controller action, my question is, Is that enough? I mean, shouldn't one test his Model objects first? Steve is using LINQ2SQL as his ORM tool, and he pretty much isn't using anything outside LINQ functionality, I mean the example only selects data, and updates by calling the LINQ built in methods; no business validation. On my real app, there is a lot of business validations that should be made, is it going to be enough (or rather easier) for me to start testing on the controller level, ignoring my Model classes (because I don't think it's a good idea)?
Waiting for your ideas Gus!

I think you'll want to have separate tests for the business-logic, in addition to controller tests.

I'm arranging my controller tests just like Steve. Basically, given the condition, does my controller contain the expected View Data? That's it. No asserts on the inner details of the data or any other business-logic - that stuff in contained in separate tests.

Following your example, I'd keep that in your Controller tests, and lets say you had some business logic preventing negative prices, you might have a separate test for things like "Product_discount_does_not_result_in_negative_price()" which is de-coupled from the web context and controller. Let's say within your Product class you have a rule that makes it's price minimum a $1 even if some so-called discount is actually more than the actual default price: (a horrible example, sorry!)

Product_discount_does_not_result_in_negative_price() {
    Product p = new Product {price = 5, discount = 10};
    Assert.IsTrue(p.price == 1); //expecting the price Get() to return 1 in this case

I think the problem you will run into if you kept the tests at the controller level, it will require to create tests for and implement the controllers before you are ready to do so.

I and my team starting new project with mvc (before write in c++) and i want to use best code style practice for mvc because its very important thing for long project. You guys who have good experience in mvc can recommend me good code styling rules? Thanks a lot

This question is too broad to be answered here. I would recommend you start with some tutorials and also there's the excellent Pro ASP.NET MVC Framework book from Steven Sanderson you might take a look at.

Also here's an excellent guide you should definitely checkout. It is based on a couple of golden rules that should be respected if you want to follow good practices.

I'm working on a ASP.Net webform app and I am wondering how long I should keep my data context around. Currently I create a context on each page load, and that context is used in every db access for the entire page load. Should I be using a context only in each method that needs it, and dispose at the end of the method? I understand that I can't access a object retrieved from the context once I exit that context's using block, but this isn't an issue with my design.

Steve Sanderson (author of Pro ASP.NET MVC Framework) has an interesting blog post on this issue. The gist of it is that the DataContext should be kept around per "unit of work", which basically correlates to a "request". I guess you could get away with shorter lifespans if you weren't modifying object and had no need to persist (update) any changes back to the DB.

You may also want to check out 'When should I dispose of a data context?' here on SO.

I need to know how to use the mvc? i am new to this technology and i decided to use it and i have downloaded MVC release 1.0 so i need to know the steps needed fro setup the framework as after setting up the framework do i need to do any configurations in VS? i need a tutorial for creating mvc project and an example with code for accessing database through mvc. and which version or release of mvc u advice me to use release 1 or 2 ?

And with respect to posting back i knew that mvc don't do post back like web forms instead it call controller so is this means that each view (.asox file) don't have a related .cs file or the .cs file is shared with many .aspx files ?

I know that my question is not clear but i got confused from articles about mvc when i ask any question or seatch about mvc many articles without practical example or direct answer to my questions in my mind

Thanks in advance

You could start out reading ScottGu's "Nerddinner" tutorial. It was originally published as part of the book titled "Professional ASP.NET MVC 1.0", but has later been released freely on his blog. I believe the tutorial covers all the basics needed to get up and running.

If you feel you need more insight, I would suggest you look to Steven Sanderson's "Pro ASP.NET MVC Framework", rather than the aforementioned book. Sanderson's book seems to cover more detail on how stuff work, and he does a great job trying to promote best practices.

Is there any way to render MVC controls or code directly within a XSLT/XSL transform file under the .NET Framework? If so can you provide me with a sample or link?

I'm reading a great ASP.NET MVC book by Apress:

In Chapter 10, there is a section called "Implementing a Custom View Engine", which shows you step by step how to implement an XSLT view engine. Its actually pretty simple (wish I could post it, but don't want to violate copyright).

I highly recommend this book to anyone (I bought and downloaded the e-book on their web site), the author really explains things well. ... OTOH, I recommend you avoid those red books with the authors' mug shots on them... unless you like books that consist mainly of screen shots and code dumps, with little effort on explaining concepts clearly.

Just wondering if anyone know if in general you can use the MVC UI helpers in a classic ASP.Net project. Obviously you would have to be mindful not to you the form helper, etc. But I have some helpers that I have built for MVC and wondering if there is anyway I can use them as is in my older project.

I know I would need to reference the MVC dll's etc, but I'm trying to think is there any traps with doing this (i.e. the page life-cycle screwing things up) or any major reasons why you shouldn't do this... My thinking is that controls work in (with some restrictions), so does it work the other way round.

Cheers Anthony

The last chapter of Pro ASP.NET MVC Framework details using MVC and WebForms side by side.

Off the top of my head, I can tell you that you must be using the Web Application project type, not Web Site.

Seeing as though ASP.NET MVC 2 Preview 1 was just released it means the way things are done may be slightly different in terms of the model. The DataAnnotation feature allowing validation to be done against properties in its model is good, but I'm not sure where to put it.

I create my models manually as recommended in Steve Sanderson's book on ASP.NET MVC, which suits me perfectly. Should I have a separate model, however, for POST data coming from a view page? So say I were creating product items, my main model may look like this:

public class Product {
    [Column(IsPrimaryKey = true, IsDbGenerated = true)] public int ProductID { get; set; }
    [Column] public string ProductName { get; set; }
    [Column] public string ProductDescription { get; set; }
    [Column] public double ProductCost { get; set; }

Now Scott's example gives us DataAnnotations so you can do:

public class Product {
    public int? ProductID { get; set; }

    [Required(ErrorMessage="Must enter a product name!")]
    public string ProductName { get; set; }

    public string ProductDescription { get; set; }

    [Range(1, 500, ErrorMessage="Too expensive!")]
    public double ProductCost { get; set; }

The latter example would have a nullable ProductID field because it would be an auto-increment field in the database. Now both of these examples would be contained in classes, and probably with the same name. Personally I don't think my main model should have these annotations in them as it shouldn't be their responsibility to validate data. So should I have separate namespaces with classes in them having different roles?

In my opinion validation is part of your model's concerns - keep them together.

I am a begineer in MVC and i need to know is it easy to use ajax with mvc ? i mean that if it is like asp applications when using ajax(JS file,web service or ajax toolkit)? I didn't try it b4 but what i need to know how can i use ajax with mvc application and i hope from any one give me an answer and put a link for articles about this topic not to put a link for general article about mvc i need a specific one about ajax with mvc and specially to be clear and with examples as i got confused from thoses articles that talked about this topic without any example.

I have read an article and noticed a code for calling ajax but i didn't understand it's structure so can any one tell me in steps and an example how to use ajax in MVC application? I am too sorry for this question that i restrict the answer but i am begineer in MVC and got confused and need a tutorial for any issue. And i need to know what are the consequences of using MVC in ? what are progress added to web programming after MVC is released in ? whate are improvements that had been added ?

Thanks in advance for any reply or answer

You've meshed up two questions into one. I'll try to address them both.

Using AJAX in ASP.NET-MVC is no different from using it in WebForms. You define an action on your controller and call it via jQuery (or any other javascript library).

Consequences of using ASP.NET-MVC? Hmm, this is a tough one. I prefer the MVC approach over WebForms because it's cleaner and easier to maintain later (this is just my viewpoint). I suggest that you read a good book on the subject, 'cos I have a feeling that you're not quite grasped the concept. I would really recommend Pro ASP NET MVC Framework.

I am learning ASP.NET MVC. I started reading "MVC in Action" and "Pro ASP.NET MVC Framework" books and noticed their text and code depend kinda heavily on some open source projects like MVCContrib, NHibernate, Castle Windsor.. etc. These are very good books with good sample projects however I need to learn raw ASP.NET MVC without cluttering my brain with other projects, even if it means I have to do things the harder ways. Plus the fact my projects could be maintained by coworkers with no knowledge about these open source project dependencies means I need to stick with pure Microsoft's offerings like Linq to SQL instead of NHibernate, no dependency injection module... etc.

Any good ASP.NET MVC books with full sample project which are just hard core MVC bits and no or minimum open source dependencies?

I think Professional ASP.NET MVC 1.0 is close to what you are looking for.

The thing is, part of the reason ASP.NET MVC was invented is to allow the developer to make use of tools and techniques like:

  1. Inversion of Control (IoC) containers
  2. Unit Testing
  3. Object-Relational Mapping (O/RM)

Now, the good news is that Microsoft has offerings for all three:

  1. The Unity Application Block is an IoC framework.
  2. MS Test is a unit testing framework.
  3. As you mentioned, Linq to SQL is an O/RM framework. There's also The ADO.NET Entity Framework, which is a bit more advanced.

I also would recommend Pro ASP.NET MVC Framework. It uses Castle Windsor for IoC, but Unity works more or less the same way. It also uses NUnit instead of MSTest, but they are likewise nearly identical.

If you want to learn ASP.NET MVC, then you'll definitely want to incorporate the stuff listed above because that's basically the whole point of the MVC framework. If you don't want to learn these things, then you'll be happier sticking with WebForms.

I have to build a web application on MVC that have a data service reference WCF as DB. I have no idea on how data persistence work on There are resource on this arguments?

I would recommend you Pro ASP.NET MVC Framework which is an excellent book about ASP.NET MVC in general. It doesn't specifically treat WCF but once you understand the concept of abstracting your data access layer into a repository inside your ASP.NET MVC application it doesn't really matter where does the data comes from. It could be a SQL database, a XML file, a WCF service, ...

The next part would be to write the WCF service. This step could be done independently from the client application. Once the service is exposed you would generate a client proxy from the WSDL by using the Add Service Reference... dialog in Visual Studio and you would be ready to call it. There's nothing specific in ASP.NET MVC for consuming a web service, it would be the same as any other type of application: console, windows, web, ...

I'm building an mvc application for users to enter an essay contest. I have an Essay table in sql server 2005. I created my domain models by dragging over the tables in the server explorer and saving the layout as, what I've named DAL.dbml.

I'm now trying to implement input field validation in the business layer using methods mentioned in Chapter 11 of Pro ASP.NET MVC Framework by Steven Sanderson. But, the author didn't create his models like I am, so I'm at a loss as to where to put my model-specific code.

I considered putting it into the auto-generated DAL.designer.cs file, but that seems problematic.

I also tried creating a new class, EssayRequired.cs, where I made EssayRequired extend Essay. This almost worked.

It successfully showed all of the validation errors.

But when it comes time to actually save the record:

EssayTable.Context.Refresh(RefreshMode.KeepCurrentValues, essay);

I'm getting this error:

The type 'DomainModel.Entities.EssayRequired' is not mapped as a Table.

Any ideas as to what I should do now? Is there a better place to put domain-specific code that won't get wiped out if the db table changes and I have to delete and re-drag the table over?

Or is there a way to tell the app that the EssayRequired object should land in the Essay table.?

Thanks, Scott

You can create a partial Essay class in the same namespace as the dbml file.

public partial class Essay
    partial void OnCreated()
       // handle additional stuff on creation, for instance.

I'm following the example website being built in Pro ASP.NET MVC 2 Framework (but using Razor instead of ASPX as I go along).

However, I've hit a snag with a partial view. I'm getting the following error:

The model item passed into the dictionary is of type
'SportsStore.WebUI.Models.ProductsListViewModel', but this dictionary requires a model
item of type 'System.Collections.Generic.IEnumerable`1[SportsStore.WebUI.Models.NavLink]'.

Here are the relevant files:


<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <link rel="stylesheet" href="@Url.Content("~/Content/global.css")" />
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")"><script>

        <h1>SPORTS STORE</h1>
    <nav class="categories">
        @{ Html.RenderAction("Menu", "Nav"); } // <!-- HERE IS THE PROBLEM -->
    <section id="content">

Menu.cshtml (the partial view):

@model IEnumerable<SportsStore.WebUI.Models.NavLink>

@foreach (var link in Model)
    @Html.RouteLink(link.Text, link.RouteValues);


namespace SportsStore.WebUI.Controllers
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using SportsStore.Domain.Abstract;
    using SportsStore.WebUI.Models;

    public class NavController : Controller
        private IProductsRepository productsRepository;

        public NavController(IProductsRepository productsRepository)
            this.productsRepository = productsRepository;

        public ViewResult Menu()
            Func<string, NavLink> makeLink = categoryName => new NavLink
                Text = categoryName ?? "Home",
                RouteValues = new System.Web.Routing.RouteValueDictionary(
                        controller = "Products",
                        action = "List",
                        category = categoryName,
                        page = 1

            List<NavLink> navLinks = new List<NavLink>

            var categories = productsRepository.Products.Select(x => x.Category);

            foreach(var categoryName in categories.Distinct().OrderBy(x => x))

            return View(navLinks);

NavLink.cs (the View-Model class):

namespace SportsStore.WebUI.Models
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Routing;

    public class NavLink
        public string Text { get; set; }
        public RouteValueDictionary RouteValues { get; set; }

EDIT: The following works fine when I use an ASCX Partial View, instead of a razor partial view:

<%@ Control Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<SportsStore.WebUI.Models.NavLink>>" %>
<% foreach (var link in Model) { %>
    <%: Html.RouteLink(link.Text, link.RouteValues)%>
<% } %>

You want to use RenderAction and not RenderPartial as RenderPartial makes a copy of the current model used for whatever other view you are currently loading and sends it over to your view (and never executes your controller method). IE RenderPartial does not call your method .. only your view. RenderAction will call your controller method and then the partial view.

In your view use:

@Html.Action("Menu", "Nav")

Your route is simply (assuming a general nav bar and no parameters)

    "NavMenu", // Route name
    "Nav/Menu", // URL with parameters
    new { controller = "Nav", action = "Menu"}

I haven't done web applications before, but I'm familiar with C#, and am trying to create a website using MVC3. I have a page with an HTML form, i have it set to use GET method, and on submit to go to a new page. The new page will load fine, and have the parameters in the URL like this:


On this new page, how do I get the parameters from the URL to work with them in C#? Essentially, I want to just take those params and put them in in a database.

I recomend you to read some book: You need to use action parameters.