Please post corrections/submissions to the MVC Forum. Include MVC FAQ in the title.

MSDN articles with Full project samples (vb and c#) (MVC 2)

MVC Best Practices
Kazi Manzur Rashid's MVC Best Practices  (great 2 part series)

Post LINQ to SQL To SQL Questions here  Post Entity Framework Questions here

Q: Should I start with MVC 1 or MVC 2?
A: ScottGu  recommends MVC 2. See http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2.aspx#7307864 where he writes I would go with ASP.NET MVC 2 for a new project.

Q: How do I get started with MVC?

MVC 3 Blogs/Posts:

  • Granular Request Validation in ASP.NET MVC 3 A++
  • How do I create a template in MVC3/Razor to pass in title and content?

    Razor provides a streamlined way of creating html helpers. In your page you can add the following:

      @helper MyClipTemplate(string title, string content) {
        <div class="Clip">
            <h3>@title</h3>
            <div class="View">
                @content
            </div>
        </div>
    }

    Then from elsewhere in the file you can just call it like a regular method:  @MyClipTemplate("The title", "The content")

MVC Must Read Blogs:

MVC 2 Blogs:

MVC 2 Code Samples:

  • ASP.NET MVC Extensions (these are really great for extensibility, OoC, multi-adaptor and more) <—NEW and recommended

Whats new in MVC 2 Code

There are three major new features in MVC 2, and several smaller ones (and bug fixes, of course).

Areas is a feature which allows segmentation and separation of your application, so that application features can be developed in isolation from one another (either in a single project or several).

Templated Input Helpers is a feature which can auto-generate forms and editors for your models, including allowing you to override templates (for example, if you always want dates edited on your site to include a drop-down Javascript calendar).

Pluggable Validation with Client-Side Validation Support allows users to get client-side validation support with jQuery Validation and DataAnnotations attributes out of the box, and supports a pluggable API to replace both client-side and server-side pieces.

You can see the ASP.NET MVC 3 Roadmap on our CodePlex site.

Stephen Walther on ASP.NET MVC

Good Tutorials

Get The Drop On ASP.NET MVC DropDownLists
Drop-down Lists and ASP.NET MVC
Adding Multiple Nested Data in ASP.NET MVC Application
Performing Validation in an ASP.NET MVC Application
Populating Hierarchical Data Using Model Binders in ASP.NET MVC Application
ASP.NET MVC Framework and JavaScript BFFF!
Creating ASP.NET MVC Helpers

Good Overviews

Awesome MVC Blogs

Client side Validation


Q: What's the difference between ResolveUrl and Url.Content and why should I favored the later ?
A:
Url.Content is preferred because it will work with WebForms, Razor or any custom View Engine. While ResolveUrl only works in Web Form View Engine. Url.Content() generates  correct subdomain-relative link. ResolveUrl() will generate an incorrect link. see 
http://stackoverflow.com/questions/2418050/should-i-use-url-content-or-resolveurl-in-my-mvc-views 

Must read on CDN usage: See http://encosia.com/2010/09/15/6953-reasons-why-i-still-let-google-host-jquery-for-me/

 

 

Routing


Route data vs. Model data - who wins?


Q: If we have in route defined parameter with same name as property at model and then we call it from strongly typed HTML helper (for example Html.TexBoxFor(x => x.PropertyName)), we get value from route parameter instead of property of model.
A: This is actually the correct behavior.  MVC has a concept called ModelState (accessible via the Controller.ModelState property) which contains information about the model the MVC request is currently working with.  The ModelState collection stores raw values submitted by the user and a list of validation errors for each of those values. For a complete example see http://forums.asp.net/p/1559541/3846809.aspx
When displaying a form, all HTML helpers look in ModelState first to get the value that should be displayed to the user, then they look at the actual model itself if ModelState doesn't contain anything useful.  The reason for this is so that user input isn't blasted away in the event of a conversion error.  For example, say that the user types "Decembr 21, 1998" (note the misspelling) for a textbox that corresponds to a DateTime property on your model.  When the form is redisplayed to the user in error, the textbox will contain the original text "Decembr 21, 1998" (which can't be represented by a DateTime) rather than the model property's actual value of default(DateTime), which is "January 1, 0001".
Now, how is this relevant to your case?  Your action method takes a parameter called username.  The existence of this parameter signals to MVC that username is user input that should be added to ModelState, thus the helpers treat username parameter with a higher precedence than the actual model itself.
If you did not intend this, remove the username parameter from your action method.  This will prevent the MVC pipeline from treating username as user input and thus prevent the parameter from propagating to the form.  If for some reason you cannot remove the parameter, call ModelState.Clear() as the first line in your action method.  This tells the MVC pipeline that there are no user input values for the current request.  Or change the route definition such that it doesn't contain a {username} path segment, as the username appears to be unused by the current request.
Using outputCache with RenderAction and Partial View - see http://forums.asp.net/p/1559041/3844428.aspx
implicit [Required] and value types - see http://forums.asp.net/p/1554316/3820542.aspx
[HttpPost] is shorthand for [AcceptVerbs(HttpVerbs.Post)].  The only difference is that you can't use [HttpGet, HttpPost] (and similar) together on the same action.  If you want an action to respond to both GETs and POSTs, you must use [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

Good Route Blogs/Threads


Q: My viewModel has user=Haacked but the view displayed from http:/localhost/home/JoeSmith shows user=JoeSmith, not Haacked as I expected.
A: See this excellent thread on ModelState.

Q: Why doesn't the following route work “{controller}/{action}/{alias}#{anchor}”.
A: Fragments can't be put into routes. Instead, using a link generator which takes the fragment as a parameter:
http://msdn.microsoft.com/en-us/library/dd492938.aspx

Comment: Routing supports optional parameters and catch-all parameters: Optional parameters let you chop off unused parameter segments at the end of the URL, but you cannot have optional parts removed from the middle of the URL. Catch-all parameters let you include all remaining URL segments at the end of a URL, but then it’s up to you to split it out into individual values.Without routing at all you can use query strings, in which case the key-value pairs are all optional with respect to the URL.

Q: Linq to SQL or Entity Framework?
A: If you’re building a new application, we recommend that you start with the Entity Framework rather than LINQ to SQL.

We continue to invest in both the Entity Framework and LINQ to SQL in .NET 4.0 and beyond. In .NET 4.0, we made a number of performance and usability enhancements to LINQ to SQL, as well as updates to the class designer and code generation. We will add new features as customer needs dictate, but we expect that the bulk of our overall investment will be in the Entity Framework, as this framework is built around the Entity Data Model (EDM).

EDM represents a key strategic direction for Microsoft that spans many of our products, including SQL Server, .NET and Visual Studio.  EDM-based tools, languages and frameworks are important technologies that enable our customers and partners to increase productivity across the development lifecycle and enable better integration across applications & data sources. See also http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx

Q: How do I get the name of the current controller and action in a view?
A: override OnActionExecuting() and access ViewData + RouteData  - See http://forums.asp.net/t/1501110.aspx

Q:Output Caching For Several Client IP's
A: See http://forums.asp.net/t/1544447.aspx

Q: How do I EnableClientValidation for only some forms on a page?
A: <% ViewContext.ClientValidationEnabled = false; %>

Call this before the form(s) for which you want to disable validation.  If you want to re-enable later in the page, just call EnableClientValidation() again (or set that property to true). See http://forums.asp.net/p/1544106/3770827.aspx

Q: How do keep values of model's unused members during update? *****
A: Stick a [Bind(Exclude = "CreatedByUserId")] attribute on the model type.  This will prevent the binder from ever attempting to set that property. See http://forums.asp.net/p/1543075/3764713.aspx

Q: Why was Default.aspx removed from MVC 2?
A: Default.aspx file should only be needed when running in IIS6 or in IIS7 Classic Mode. Neither Cassini (the built in VS web server) nor IIS7 Integrated Mode (the default) need default.aspx. The reason we took Default.aspx out is that there are many steps required to get ASP.NET MVC to work on IIS6 and IIS7 Classic Mode and having Default.aspx in the project doesn't help very much anyway since there are so many other steps.

Q: MVC is not working with GridView/ListView
A: ASP.NET MVC does not support data sources and does not support the GridView. If this is your preferred method of programming, you should use ASP.NET WebForms. Alternatively consider the Telerik ASP.NET MVC Grid

Q: MVC or Web Forms?

Q: ViewData v. tempData

  • http://www.squaredroot.com/2007/12/20/mvc-viewdata-vs-tempdata/
  • http://stackoverflow.com/questions/313572/what-is-tempdata-collection-used-for-in-asp-net-mvc
  • http://stackoverflow.com/questions/173159/difference-between-viewdata-and-tempdata
  • http://forums.asp.net/p/1486424/3482503.aspx


    Q:How do I figure out route order?
    A:Use Phil Hacck's route debugger - Also see Manually unit testing routes in ASP.Net MVC

    Q: What is the correct way to write a delete action?
    A: See

    Q: How do I bind my model to a List?
    A: See Phil's blog Model Binding To A List http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

    Q: My jQuery/JSON works fine on my machine, but doesn't work on the server.
    A: Your URLs are not getting resolved correctly. See http://forums.asp.net/p/1486162/3484734.aspx

    Q: How can I find memory leaks and profile memory usage of my MVC app?
    A: Use the CLR Profiler: http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&displaylang=en  
    Thomas M. has a nice blog of how to use the profiler with ASP.NET: http://blogs.msdn.com/tmarq/archive/2007/06/09/the-clr-profiler.aspx

    Q: I have a view where the user fills out a form, submits and the data is displayed on a confirmation page. They must submit the confirmation page before the DB is updated (or their credit card is charged). The problem is, the confirmation page is nothing but text; so when they submit that View, nothing will be passed to the controller. The controller has no way of knowing what information the user entered 2 views ago.
    A: The easiest thing to do would be to shove it into Session (if Session is enabled).  Otherwise use hidden input fields or the Html.Serialize() helper from Futures.  Absolutely do not use TempData for this.  Hidden form fields is the right answer for scalability reasons. TempData is the wrong reason because if the user refreshes the confirmation page, then the TempData will be destroyed. Also, if Session is disabled, then the default TempData provider is also broken (since it's based on session).

    Q: I’m trying to pass my custom object via RedirectToAction and it’s not working, why?
    A: RedirectToAction() works by shoving data into the URL.  Since an AbcFilter can't be put into the URL, this doesn't work. Try using TempData for this instead: See http://forums.asp.net/p/1519057/3644229.aspx

    Q: Can MVC 1 be installed on Visual Studio 2010?
    A: No, VS2010 is not compatible with MVC 1.0. For that you will need to stick with VS 2008. See http://haacked.com/archive/2009/10/20/vs10beta2-and-aspnetmvc.aspx

    Q: In my custom view engine, ViewLocationCache  is always empty, why?
    A: See http://forums.asp.net/p/1518585/3642807.aspx

    Q: Is there a way to precompile MVC application including code and views for deployment?
    A: You need to install the Visual Studio Web Deployment add-in (see http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en)  In your MVC solution, right click on the MVC project and select "Add Web Deployment Project..." (thanks to Jacques) --- running the command line utility using aspnet_compiler will also do the job. The command line is:(framework directory)\aspnet_compiler -v /virtualDirName outputdirectoryName

    Q: I'm using partial views and jQuery. When I use jQuery to do the post and updates to the page my javascript fires as I would expect. If i let Ajax.BeginForm handle it the javascript doesn't execute. Why?
    A: When you update the DOM with new HTML, the browser doesn't automatically execute scripts in the new bit of HTML. MVC Ajax helpers would need to parse the partial HTML and try and execute the scripts, which is tricky and something we don't currently do.
    One approach you could take is to look at jQuery live events. - source http://forums.asp.net/t/1440121.aspx

  • JQuery and partial views in an ASP.NET MVC application 
    Combine/Compress/Minify JS and CSS files in ASP.NET MVC
    How to load partial view dynamically in ASP.NET MVC using JQuery

    Q: How do I mix Web Forms and MVC?
    A: see

  • http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc

  • http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx

  • Free Sample Chapter — Chapter 13: Best of Both Worlds: Web Forms and MVC Together http://media.wiley.com/assets/1539/15/professionalaspnet35mvc_chapter13.pdf


    Q: Is it possible use an enums in a controller action method?
    A: Yes - See http://forums.asp.net/t/1440432.aspx

    Q: What does the following do:
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
    A:  Tells the routing engine to ignore request that end in .axd or .aspx (.aspx needed for MVC on IIS6)

    Q: Invalid viewstate exception when using AntiForgeryToken error on Hosted site.
    A: You can read more here: How To Fix the: “Validation of viewstate MAC failed” Error (ASP.NET MVC)

    Q: Can open generic methods be used with controlers?
    A: Do you mean an open generic method, such as:
    public class MyController : Controller {
        public ActionResult SomeAction<T>(T myParameter) { ... }
    }

    Or a method that is generic on a class:
    public class MyController<T> : Controller {
        public ActionResult SomeAction(T myParameter) { ... }
    }

    Example #1 is not supported in ASP.NET MVC because we don't know the type of "T". Example #2 is technically supported in MVC since by the time we get to the method we already know what the "T" is. However, the default controller factory in ASP.NET MVC cannot construct generic classes. If you have a controller factory that can create MyController<T> then ASP.NET MVC can call the action method on it.

    Q: I thought the default http handling was synchronous, but that's not the behavior I'm seeing.
    A: With the addition of AsyncController in MVC2, the MvcHandler class needs to be an IHttpAsyncHandler now, which means that as far as the ASP.NET core runtime is concerned, the entry points are now BeginProcessRequest and EndProcessRequest, not ProcessRequest. See http://forums.asp.net/p/1547898/3788871.aspx

    Q- Why is Html.ValidationSummary  is inconsistent in my app.
    A: Validation happens during model binding, either implicit binding via action parameters or explicit binding via calls to (Try)UpdateModel.

    Q: How do I preserve HTML in error messages?
    A:You're likely going to be more interested in the workings of Html.ValidationMessage() and our other helpers rather than the workings of AddModelError().  AFAIK all of the UI helpers encode their output, so HTML like <br /> will always be rendered as &lt;br /&gt;.

    If you want to display the error messages as HTML, you'll have to create a new helper like Html.FormattedValidationMessage() which is based off of Html.ValidationMessage() but doesn't encode the data.  Take a look at the source for Html.ValidationMessage() and you'll find that it's not a very complex method.  It should be fairly straightforward to copy that code into a new method that leaves out the line that does the HTML encoding.

    See http://forums.asp.net/t/1377525.aspx (this thread also shows the wrong way to implement error messages with HTML, the wrong approach opens you up to a potential cross-site scripting attack


    Q: I added a new field to my model - I did not mark it required but when I don't include it on submit/Post - ModelState.IsValid is false and I get an error "the field value is required."
    A:Properties of non-nullable types are by definition mandatory, even without [Required].  A value ("", which we convert to null) is submitted back to the server, and we can't convert that value to an Int32, so binding fails.  If you need a field to be optional, you should make it nullable.  In that case, we can successfully store a null value in the property.

    Q: Ho do I create a general validation attribute for checking uniqueness in a linq to sql data context?
    A: See http://forums.asp.net/t/1512348.aspx#3608029

  • Q: What's the correct way to get the controller name and action from an httpContext object?
    A: You can't; you require at minimum a RequestContext object.  If you have a RequestContext object, you can call RouteData.GetRequiredString("controller") / GetRequiredString("action").

    Q: My MVC app has a class with that initializes a variable ( DateTime.Now in this case). This value seems to be cached. WHat's going on here?
    A: HttpApplication instances are cached and reused but the value of the variable is indeterminite because the the constructor can run again at any moment. See http://forums.asp.net/p/1532702/3719493.aspx

    Q:How do I use partial views to display data on every page using site.master? is it necessary for every controller to deliver the model-data?
    A: Yes, OR If you're using ASP.NET MVC 2, You can use RenderAction instead of RenderPartial. This will allow you to centralize the data collection and partial view into a mini-action.

    Q: I'm not getting the validation error message I specify.
    A: It could be what you're talking about here isn't validation, but model binding failures. You can use resources for this message. See http://forums.asp.net/t/1512140.aspx

    Q: System.EntryPointNotFoundException: Entry point was not found. when unit testing html helpers
    A: See http://forums.asp.net/t/1480068.aspx

    Q: query string parameters and view model fields binding problems?
    A: See http://forums.asp.net/p/1526013/3682883.aspx 

    Q: When I upload large files I get a HTTP 404 error.
    A: I fixed it by just maxing out the maxRequestLength value and not setting any other property values.

    <httpRuntime maxRequestLength="2097151"/> See also

    http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx

    Q: How do I call halt the MVC pipeline when my controller has an exception? How do I call Response.End()?
    A:Response.End() is not supported in MVC 2 / 3.  Instead, what you can do is throw an HttpException, passing to the constructor the HTTP status code you want.  This will halt control flow of the application.
    Q: Is there a VB.Net equivalent to the "<dynamic>" attribute of a C# based view?


  • A: Turning "option strict" off.  VB.NET can also use the new "dynaming" type, but it doesn't work in medium trust in VB.NET, so we recommend people turn off option strict instead. The normal MVC way is to return an ActionResult from your action method.  (Take a look at MVC 3's HttpStatusCodeResult, for example.)  The ActionResult would be responsible for setting the status code and status description values.  If throwing exceptions works best for your control flow, you could write a filter (subclass FilterAttribute and implement the IExceptionFilter interface).  In the OnException method, swallow the exception (set filterContext.ExceptionHandled = true) and set the status code and status text to your desired values from there.
    ASP.Net Development server (from Visual Studio) AKA Cassini eats the status description. You need to test this with a real IIS server.  See http://forums.asp.net/t/1624919.aspx



    Binding



  • Q: I’m trying to use DataAnnotations to force an input field to the right type – but when the wrong data type is entered I don’t get the error message I used in my DataAnnotations , I get the error “value is not valid for this field", and the value is null, not the incorrectly entered data.
    A: Validation attribute are applied after model binding. The message you see comes from the model binder when it catches a wrong format exception generated by the converter. For more info see http://forums.asp.net/t/1608322.aspx


    Q: I am unable to get value for Html.TextBoxFor(m = > m.name) in view.

    A: This value is only automatically maintained if the value is retrieved via model binding. It's the model binding process which puts the current value into ModelState, which is how we automatically round-trip things. If you don't somehow model bind "name", then the value won't be preserved. You either need to model bind it, or set the value into ModelState by hand. see http://forums.asp.net/p/1581418/3987553.aspx

    Q: If a have a Html.TextBoxFor input field in my view bind to a property called test on my viewmodel...When changing this value in the post action in the controller and then returning View(viewModel), the value is discarded!
    A: You can override this behavior by removing the ModelState entry for the property. All the HTML helpers get the previously posted value for re-display from the ModelState dictionary.




     
    Debug


  • Q: The VS 2010 debugger is showing the following exception "This property cannot be set to a null value." – But when I run the code outside of Visual Studio I don’t see the error.
    A:
    This is expected behavior.  Internally, MVC is setting the model's ISBN property to null.  This is triggering EF validation within the property setter and is throwing an exception.  MVC swallows this exception and moves on to the next property of the model.

    You'll see the debugger activate on this exception if you have Visual Studio set up to break on CLR exceptions (via the menu Debug -> Exceptions).  If you're not running under a debugger or don't have the debugger configured to pause on exceptions, you won't see this exception.  Hitting F5 (to continue) from within the debugger will allow program execution to continue as normal. – See  http://forums.asp.net/p/1596779/4052875.aspx#4052875


  • security
     

    Q: How do I hide sensitive information from my model (Like SSN, salary, etc)?
    A: What most developers do is store an identifier instead of the actual sensitive data.  For example, if you're updating an Employee (from the table Employees), each Employee might contain sensitive information like the tax identification number, salary, family members, etc.

    Instead, one option is to send a single hidden field containing only the employee id (which presumably isn't sensitive information).  When the action executes, it reads this hidden field to perform an Employee lookup by number against the database.  Now the action has access to all of the sensitive information without having exposed it in the form.

    If you go this route, you'll have to take some other precautions.  For example, you'd have to verify that the person submitting the form actually has access to that particular Employee record (otherwise they could tamper with the EmployeeId field in the form).  You'll also have to prevent over-posting if you're binding directly to an Employee object.  (This latter point is why I always implore people not to bind directly to their database models, but instead to use view-specific models and map them to database models as necessary.)


    Q: How does <authorization> <allow roles="SomeRole"/> in web.config work in MVC
    A: In MVC, your resources are controllers, not URLs.  So if you wanted to restrict access to an entire AdminController, for example, you'd put[Authorize(Roles = "Administrator")] on the controller class.

    If you need to secure a group of controllers, put the attribute on a AdminControllerBase class, then have each controller you need to secure subclass that type.  The framework will automatically apply the attribute to the subclassed types.

    In ASP.NET MVC this is done with a special kind of filter namely IAuthorizeFilters. If you define them on controller level you define them for all your actions and if you have a base controller you define them for all controllers that are derived from this base controller.  see http://forums.asp.net/p/1591248/4032140.aspx




    HTML Encoding extensibility http://forums.asp.net/p/1568353/3931354.aspx

    Q: I have a situation where I need a finer grain security within my page than what is available with forms authentication, membership and roles.
    A:  See http://forums.asp.net/p/1594644/4046084.aspx

    Q: I have multiple tabs open to a web site. When I close one tab, Formsauthentication doesn't clear.
    A: What is the particular problem you're trying to solve here?  "I need to log a user out when he closes a browser tab" isn't a problem; it's a means to an end.  Why do you need to log the user out when he closes the tab?  If you back up to the original problem, perhaps we'll all find another way to solve it.

  • In general, browsers store temporary cookies (including the ASP.NET FormsAuthentication cookie) for the entire lifetime of the browser process.  Since closing a tab doesn't kill the browser process itself, the temporary cookie sticks around until the browser is fully closed.  So if within the same browser process you open a new tab and visit your web site, the browser will send the temporary cookie to the site.  This isn't a flaw or a failure; this is just how cookies work. See http://forums.asp.net/p/1595989/4056833.aspx

    Q: I have code in a asp.net application that runs along side other 3rd party code in the same application. I am inserting a custom object that has some information I want to keep private into the HttpContext object so that later in the pipeline some of my other code can retrieve it. Sessions, application, cookies are not an option here.
    A:

    Is your component fully trusted and you want to prevent partial trust code from accessing it?  If so, just wrap the object to be stored into Items in a type that's internal to your application, and protect the class with a demand:
    view plaincopy to clipboardprint?

       1. [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")] 
       2. internal sealed class MyWrapper { 
       3.   internal object WrappedObject; 
       4. } 

    [PermissionSet(SecurityAction.LinkDemand, Name="FullTrust")]
    internal sealed class MyWrapper {
      internal object WrappedObject;
    }

    You can put an instance of MyWrapper into HttpContext.Items.  Partial trust code will be able to get the opaque instance of MyWrapper by enumerating Items, but they can't look at WrappedObject since they don't fulfill the required demand.  When your fully trusted code reads the MyWrapper instance back out, you're free to look at WrappedObject since your own code implicitly meets the required demand.

    Edit: This won't prevent replays, but you can code defensively around that, e.g. by keeping a reference to the correct HttpContext inside of the wrapper.  This sample is meant to prevent partial trust code from creating or inspecting instances of MyWrapper.

    See http://forums.asp.net/p/1589711/4029323.aspx

    Q: How do I create an authorize filter that take parameters?
    A: See http://forums.asp.net/p/1589414/4024485.aspx

  • Q: Why is a " A required anti-forgery token was not supplied or was invalid" Exception thrown when I follow the sequence:

    1. Login (Successful)
    2. Go back (via browser back button)
    3. Login (Exception)

    with   

    1. [HttpPost] 
       2. [ValidateAntiForgeryToken] 
       3. public ActionResult Login(LoginModel loginModel, string returnUrl) 
       4. { 
       5. // validate login, set authcookie 
       6. } 

  • A: This behavior is correct.  The anti-forgery tokens are tied to specific users (or the 'guest' user if the current user is not logged in).  The first time the form is generated, the user is not logged in, so a token is generated for the user GUEST.  The user hits the login button, the token validates correctly (since the user has not yet been logged in), your controller logs the user in, and life is good.  Let's assume he logged in as JOE.

    Now, if the user hits the back button, he'll be taken back to the original form.  (More specifically, he'll see the cached version of the original form, complete with GUEST token.)  When he tries to submit the login again, the GUEST token cannot be used for a request coming from JOE, so the system rejects the token.

    This is pretty much the same behavior you'll see at some banking and other web sites, many of which don't allow you to use the back button once you've logged in.  Their tokens follow a similar pattern of being tied to a specific user, and if an old token is used with a logged-in user they will fail.

    Presumably this shouldn't be problematic, as the particular scenario under consideration (submitting the exact same form under two different identities) isn't something most users do and isn't something that's always expected to work properly.  If this is however a problem for you, you could remove [ValidateAntiForgeryToken] from the Login() action.

  • Q2 (continued):  if I create a custom ActionFilter it does not fire before the ValidateAntiForgeryToken.

    A: ValidateAntiForgeryTokenAttribute is an authorization filter (it implements IAuthorizationFilter), while your filter is a regular action filter (it implements IActionFilter and IResultFilter via subclassing ActionFilterAttribute).  Authorization filters are always executed before action filters, regardless of ordering.  Ordering can only be used to order authorization filters relative to other authorization filters, action filters relative to other action filters, etc.

    Instead, your filter should subclass FilterAttribute (instead of ActionFilterAttribute) and implement the IAuthorizationFilter interface.  From the OnAuthorization() method, perform the necessary check + redirect.  Since both your attribute and the [ValidateAntiForgeryToken] filter are authorization filters, their Order properties will be respected.

    Filter execution is grouped by filter type: authorization filter, action filter, response filter, and exception filter.  *All* of the authorization filters go first, then *all* of the action filters, then *all* of the response filters.  Within these particular groups, ordering is determined by the rules detailed at http://msdn.microsoft.com/en-us/library/dd381609.aspx (Order of Execution for Action Filters). By the rules detailed at this article, the Controller.OnAuthorization() method will execute before any authorization filter, regardless of the filter's Order. For more details see http://forums.asp.net/t/1560362.aspx


  • The [RequireHttps] attribute can be used on a controller type or action method to say "this can be accessed only via SSL."  Non-SSL requests to the controller or action will be redirected to the SSL version (if an HTTP GET) or rejected (if an HTTP POST).  You can override the RequireHttpsAttribute and change this behavior if you wish.  There's no [RequireHttp] attribute built-in that does the opposite, but you could easily make your own if you desired.

    There are also overloads of Html.ActionLink() which take a protocol parameter; you can explicitly specify "http" or "https" as the protocol.  Here's the MSDN documentation on one such overload.  If you don't specify a protocol or if you call an overload which doesn't have a protocol parameter, it's assumed you wanted the link to have the same protocol as the current request.

    The reason we don’t have a [RequireHttp] attribute in MVC is that there’s not really much benefit to it.  It’s not as interesting as [RequireHttps], and it encourages users to do the wrong thing.  For example, many web sites log in via SSL and redirect back to HTTP after you’re logged in, which is absolutely the wrong thing to do.  Your login cookie is just as secret as your username + password, and now you’re sending it in cleartext across the wire.  Besides, you’ve already taken the time to perform the handshake and secure the channel (which is the bulk of what makes HTTPS slower than HTTP) before the MVC pipeline is run, so [RequireHttp] won’t make the current request or future requests much faster.

    Q: How do I create an authorize filter in asp.net mvc?
    A: See http://forums.asp.net/t/1589414.aspx



    Q: How do I create a single custom authorization attribute to be added to controller actions that require authenticated users.
    A: authorization or other security decisions must never be made based on the current area, e.g. examining the current route to determine which area the current request belongs to.  The only supported way of accomplishing this is to put an [Authorize] or other similar filter which doesn't depend on the current area on a base controller, then making sure that each controller within an area subclasses that base controller. See http://forums.asp.net/p/1531406/3708509.aspx for more details
    Force MVC Route URL to Lowercase  and http://goneale.com/2008/12/19/lowercase-route-urls-in-aspnet-mvc/
    Q: How does ModelMetadata work? How does Html.Editor()  get metadata?
    A: See http://forums.asp.net/p/1533703/3719507.aspx

    Q: How do I move the authorization out of being hard-coded in the app and into a DB table where it can then be administered by the apps admin functions?
    A: See http://forums.asp.net/p/1533590/3738490.aspx

    Q: How do I generate HTTPS URLs?
    A:http://forums.asp.net/p/1526452/3684203.aspx

    Q: How do you get a redirect to send an HTTP POST instead?  This is necessary for passing control to PayPal's payment page.
    A: See http://forums.asp.net/p/1542915/3765160.aspx

    SECURITY


  • Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper   Steven Sanderson’s awesome MVC CSRF blog posting.  

    Q:How Can I Create A secure Form URL?
    A: http://forums.asp.net/p/1514028/3616654.aspx

    Q: I have a custom Authorize attribute, which implements OnAuthorization. In the default OnAuthorization, an HttpUnauthorizedResult is set when there is an authorization failure. Can I intercept this ActionResult somewhere and take a specific action based on it. I do not want to put all the redirection logic etc. in OnAuthorization
    A:In general your subclassed AuthorizeAttribute should not override OnAuthorization().  Override HandleUnauthorizedRequest() instead and set the filterContext.Result property as appropriate from within that method.


    Q: How do I prevent a user from sending us confidential data (credit card number, SSN, etc.) over an unsecured channel (HTTP)?
    A: You can't. If the user sends confidential data via HTTP you can't go back in time and undo the transmission. Action methods that handle posts of confidential data should use the [RequireHttps] Attribute;  the action method will ignore the post and force the sender to use HTTPS.

    Q: Will the [RequireHttps] Attribute prevent Man in the Middle Attacks (MITM) or DNS cache poisoning attacks?
    A: The [RequireHttps] Attribute can't prevent MITM or DNS cache poisoning attacks, but HTTPS in general does protect against these.

    Q: How do I intercept HttpUnauthorizedResult() when it’s  set in OnAuthorization?
    A: In general your subclassed AuthorizeAttribute should not override OnAuthorization().  Override HandleUnauthorizedRequest() instead and set the filterContext.Result property as appropriate from within that method. See http://forums.asp.net/t/1460610.aspx

    Q: How do I handle exceptions in a View?
    A: You can use elmah.  Check out this article : http://volaresystems.com/Blog/post/Handling-Exceptions-in-ASPNET-MVC.aspx   and go to How to wire this up in ASP.NET MVC section for more info.

    [HandleError] will catch exceptions from views and HTML helper methods.  But since you can only put it on a controller or an action, it’s not global.

    You can use ELMAH to do exception logging application-wide (not just within MVC) and across multiple controllers.  Hanselman also wrote about this - http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx.

    Q: Switching between HTTP and HTTPS in ASP.NET MVC2
    A: See http://forums.asp.net/p/1548464/3807551.aspx
    Q:i'm having the "A potentially dangerous Request.Form value was detected from the client" error
    A: see http://stackoverflow.com/questions/2019843/a-potentially-dangerous-request-form-value-in-mvc-2-asp-net-4-0/2022528#2022528.
    It's best to think of .aspx / .ascx views in MVC applications as templates rather than proper pages.  The MVC framework will run the template (which might contain basic code snippets like calling helpers), but it's not guaranteed to execute the page pipeline in any sane fashion.  This implies that events might execute out of order, with uninitialized parameters, or not at all.  But this is OK for MVC, since views shouldn't be hooking such events in the first place.
    The DataTypeAttribute does not contain any validation logic itself. The hooks are there for people who are writing custom data types that derive from DataTypeAttribute to not only contain the data type (and appropriate formatting information) but also validation logic.
    if your route has an {id} segment, that may be interfering with the ?id=... part of the query string being generated by jQuery.  If your route definition assigns a default of id = "", try changing it to id = UrlParameter.Optional.  That basically tells the binder "RouteData might not contain anything useful for id, so check QueryString instead." see http://forums.asp.net/p/1553400/3814861.aspx

    Q: How do I prevent the error A potentially dangerous Request.Form value was detected from the client  with .Net 4 (ie, without using <httpRuntime requestValidationMode="2.0" />)?
    A:You can write a custom request validator which excludes certain fields from validation but still validates every other field.  See http://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator.aspx for full documentation on how to do this.In brief, your IsValidRequestString() method would have the following logic:

    - If the current URL (as read from the HttpContext object) is ~/somepage *and* the current collection is form *and* the current key under consideration is "field-to-exclude", return true to signal that this value is OK.
    - Otherwise call base.IsValidRequestString() to run the default validation logic over this field.

     

    ASynchronous

    All about the The AsyncTimeout filter: See http://forums.asp.net/p/1564303/3926107.aspx
    Q: Do I need to use asyncController to allow my user concurrent ajax requests?
    A: See http://forums.asp.net/p/1567598/3918063.aspx

    Q: How do I implement multiple synchronization points on Controller async action?
    A: You can do this using manual counters.  In short:
    - Call AsyncManager.OutstandingOperations.Increment() once at the very beginning of the request.  Don't touch OutstandingOperations again until the very last step below.
    - Kick off your three parallel operations.  Keep your own separate counter (initialized to 3).  As each operation completes, decrement this counter by one.
    - When your internal counter hits zero, you know that the first set has completed.  Kick off your next set (with a separate counter, initialized to the number of items in the new set).  As each operation completes, decrement this counter by one.
    - Repeat as necessary for each set.
    - When all sets have completed, call AsyncManager.OutstandingOperations.Decrement() to complete the work.
    The reason this works is because from the AsyncManager's perspective, your entire block of work is one gigantic asynchronous operation (hence why the counter was incremented / decremented only once).  You're going to be kicking off extra work as part of this single block, but AsyncManager doesn't know of or care about that.
    See http://forums.asp.net/p/1531002/3722202.aspx#3722202



    Templates
    The Html.Display/Editor functionality is designed to work with raw objects with properties, not dictionaries. See http://forums.asp.net/p/1533792/3720119.aspx for more details.

    Q: Why shouldn’t I use textwriter? (*****)
    A: See http://forums.asp.net/t/1526810.aspx

  • http://forums.asp.net/t/1527149.aspx  EditorFor great thread.

    Q: How do you validate passwords?
    A: See http://forums.asp.net/p/1544798/3773741.aspx

    Q: I'm writing a custom editor template and display it via:
      <%=Html.EditorFor(model=>model.MyProperty, "MyTemplate") %>

    In my ascx, I can access the property name and the model type thanks to the ModelMetadata.PropertyName and ModelMetadata.ContainerType. But how can I get a reference to the entire model itself?

    A: Use the overload of EditorFor that allows you to pass additional ViewData values, and stash the outer model in a ViewData item so that you can retrieve it inside your template.  OR ViewContext.Controller.ViewData.Model will work, you need to cast this to Model type.


    Q:How do I use HttpContext.Cache.Add with MVC?
    A: Overriding the OnActionExecuting method in the controller is the correct thing to do. The constructor of the controller is way, way too early. At that point MVC itself barely even knows what's going on. By the time the OnActionExecuting method executes you can get a lot more info about what's going on, including the ControllerContext, which is where the Cache property hangs off of.

    Q:How do I parse string into javascript date object based on locale? (Globalization)
    A: See http://forums.asp.net/t/1481185.aspx and http://stackoverflow.com/questions/817046/what-about-script-globalization-of-microsoftajax-js-in-asp-net-mvc  (see next Q/A)

    Q: How do I pass localized dates as query strings?
    A: The problem with automatically parsing dates from the query string with the user's locale is that we have no idea where they came from. If the server is putting dates into URLs, it clearly can't do that using the user's locale, because then you will have non-canonical URLs (and worse, URLs which point to the wrong content depending on the user's locale). In fact, even if the date came from the user, you're still generating a non-canonical URL which the user could pass along to another user and inadvertantly send them to the wrong place.
    When the values come from POSTed form fields, we know they came from the user and can then apply the user's locale when binding. - from http://forums.asp.net/t/1461209.aspx

    Q:how do I generate a URL for AJAX?
    A: var myUrl = '<%= Url.Action("GetDetails","Home"); %>';

  • $.ajax({
      type: "POST",
      url: myUrl });

    see http://forums.asp.net/t/1461234.aspx

    Q: How do I use the ajax client library in MVC?
    A: See Using Ajax Client Controls  on http://www.asp.net/ajaxlibrary/learn.ashx

  • Q: There are 2 views in my mvc app that show a list of items. Both provide the ability to edit them by redirecting to a Edit view. How can I provide a back link on the Edit form that takes the user back to the list they were on?
    A: create a hidden field in Edit view and save the UrlReferer in it. On postback use this field value to track the back address.
    <%=Html.Hidden("UrlReferer",Request.Form["UrlReferer"]??Request.UrlReferer.ToString())%>
    http://forums.asp.net/t/1461072.aspx

    Q: How do I reference scripts?
    A: <script src="<%= Url.Content("~/Public/Scripts/RunActiveContent.js") %>" type="text/javascript"></script>
    CDN is the best approach:  (see Microsoft Ajax CDN and the jQuery Validation Library )
    <script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.3.2.js" type="text/javascript"></script>

    Q: How do I get started on jQuery with MVC?

    Q:What's the difference between temp data, view data and session data?

    Q: How do I pass data on a redirect?
    A: TempData - see http://blogs.teamb.com/craigstuntz/2009/01/23/37947/

    Q: L2S or EF?
    A:http://dotnetaddict.dotnetdevelopersjournal.com/adoef_vs_linqsql.htm

    Q:Is browser still connected? if the browser is still connected before attempting to return results or doing more work?
    A:There aren't very many reliable way of detecting this state. You can try to make it a bit better by writing some JavaScript that detects when the browser navigates away and sends a quick message to the server to tell it to stop the long operation. This method is unreliable, though, since if the user shuts down their browser or unplugs their computer the server won't get the message. The hard part is how does the server correlate the long-running process with the new message and know that they are the same.

    Q: Why do I get the following error?
    FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\.\" in the path.
    A: COM1, COM2, COM3, COM4, LPT1, LPT2, CON, AUX, PRN are reserved file names, rename your view (append X) and starting with ASP.NET 4, you can rename the action back to the reserved name via:

    [ActionName("con")]
    public string  conX() {
    return "From string ActionResult conX()";
            }

    See http://blog.bitquabit.com/2009/06/12/zombie-operating-systems-and-aspnet-mvc/

    Q: Return File does not work with non-US-ASCII
    A: That is a limitation in ASP.NET MVC 1 (file name must be US-ASCII ) - Fixed in MVC 2 RC. See more details here (and a workaround): http://forums.asp.net/t/1448041.aspx  and http://forums.asp.net/t/1483316.aspx  - This is documented in Controller.File Method (String, String, String) (System.Web.Mvc)

    Q: why doesn't "return javascript("alert(hello);") work? 
    A:For the JavaScript result to work in an action method the action method must be executed via an AJAX request. In other words, you can't have a regular link tag that points at this action method. You have to create a special link using Ajax.ActionLink or using Ajax.BeginForm.

    Q: How do you pass parameters using RedirectToAction?
    A: You can pass parameter as GET parameters  or using TempData. TempData is better solution in most cases.
    http://www.augi.cz/programovani/aspnet-mvc-passing-data-when-redirecting/
    http://forums.asp.net/t/1470201.aspx

    Q:How do I localize  Data annotations, ErrorMessageResourceName, ErrorMessageResourceType
    A: See http://forums.asp.net/t/1433699.aspx

    Q: How do I replace the error message ""A value is required" with my own custom error message?
    A: See http://stackoverflow.com/questions/646270/asp-net-mvc-custom-validation-message-for-value-types/1374653#1374653

    Q: How do I move sessionID from the default (cookie) to the querystring?
    A: See http://forums.asp.net/t/1480365.aspx

    Q: How do I keep track of wrong answers on a form submit (limited guesses on security question)?
    A: See http://forums.asp.net/p/1476843/3460584.aspx

    Q:I'm setting the value of a hidden with tempData, but the value is always overridden on postback. What's the problem?
    A: On postback, all input helpers -- including hidden -- render the value that's in ModelState rather than the value that's provided from ViewData or the helper method. The assumption is that if you're re-rendering the form on postback, then it's because there was an error, and we should show the values the user typed rather than the values in the object. See http://forums.asp.net/p/1476843/3460584.aspx
    In your controller action, you could remove the hidden value from ModelState to force it to use the new value.

    Q: I want to pre populate some of the form fields from browser cookies. How to set and load cookies in an mvc app?
    A: The same way as in any ASP.NET application - via Cookies property on Request and Response objects. These objects are accessible from controller via HttpContext.Request and HttpContext.Response properties. So just use HttpContext.Request.Cookies and HttpContext.Response.Cookies from your controller. See http://forums.asp.net/t/1482840.aspx

    Q: XHTML header indentation format is not respected for some tags - why?
    A: In the default MVC template the <head> tag in the Site.master file (in the ~/Views/Shared folder) is marked as runat="server". This special attribute gives the tag additional behavior that in some cases is nice, and in other cases it can cause formatting problems. You can remove the runat="server" attribute from the <head> tag but that can cause certain URLs to map incorrectly. The following will not work

    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

    You’ll have to call Url.Content() instead, like we do for javaScript files. The only thing you lose at that point is Design View in VS (it’ll work but you won’t see the CSS styles). see http://forums.asp.net/t/1482073.aspx 

    Q: How do I prevent Invalid viewstate exception when using AntiForgeryToken?
    A: See http://forums.asp.net/t/1479165.aspx

    Q: How do I prevent the favicon error ( System.Web.HttpException was unhandled by user code
      Message="The controller for path '/favicon.ico' was not found or does not implement IController.")
    A: This is just a debugger notice you can ignore or add routes.IgnoreRoute("favicon.ico"); (See line 3 below)

       1: public static void RegisterRoutes(RouteCollection routes) {
       2:             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
       3:             routes.IgnoreRoute("favicon.ico"); 
       4:  
       5:             routes.MapRoute(
       6:                 "Default",                                              // Route name
       7:                 "{controller}/{action}/{id}",                           // URL with parameters
       8:                 new { controller = "Home", action = "Create", id = "" }  // Parameter defaults
       9:             );
      10:  
      11:         }



    Q: How do I create  Cascading Drop Down boxes in MVC?
    A: http://stackoverflow.com/questions/705540/asp-net-mvc-cascading-drop-down

    Q: Authorize filter and what it exactly does.
    A: See http://forums.asp.net/t/1382315.aspx

    Q: How do I create a custom role provider for MVC?
    A: See http://forums.asp.net/t/1382315.aspx

    Q: How do I keep track of posts to security questions (wrong answer) to limit a client to N guesses?
    S: See http://forums.asp.net/p/1476843/3438217.aspx

    A: Routing links - see http://forums.asp.net/t/1476922.aspx and ASP.NET MVC - Prevent Image Leeching with a Custom RouteHandler  and http://forums.asp.net/p/1515157/3622809.asp

  • When constructing an outbound route, the system finds the first match that is legal and uses that to construct the route. What makes a route legal is that all the required values are present, and all the restrictions are satisfied. Any values which are leftover which aren't part of the route itself will be added as query string values.



    Q: How do I enable MVC on IIS5.1 (XP) or IIS 6?

    Q: How do I use JSON in MVC?
    A: See http://weblogs.asp.net/mehfuzh/archive/2009/04/28/using-of-json-result-in-asp-net-mvc-1-0.aspx

    Q: I have an Ajax.ActionLink that loads a partial view into a div, using a get method. The problem is, the user can just visit controller/AjaxAction directly, like they could with any action method. Basically, I need an ActionMethod that accepts HttpVerbs.Get, but can only be called by Ajax; as opposed to being called as a normal action.
    A: check if Request.IsAjaxRequest() is true or false.  If it is false, you could redirect somewhere else for example.  If it is true, then continue processing.You could even create a custom action filter that checks this and makes the decision.

    Q: In WebForms, I use Page.Request.ServerVariables["LOGON_USER"];  to get the current logged in user. How do I do this in MVC?
    A: Have the controller put it in ViewData.  (thanks paul.vencill )
    ViewData["username"] = User.Identity.Name;

    Q: Why do I get the following build error: The "xxx" task failed unexpectedly.  System.UnauthorizedAccessException: Access to the path 'C:\Path...' is denied.
    A: You're probably hitting a known bug related to source control systems which leave your source files as read-only by default (like TFS). The first copy succeeds because there isn't anything there, but the second copy fails because it refuses to overwrite the read-only copies of the files from the first time around. There is no work-around today besides checking out all the files that will be copied so that they're read-write instead of read-only.

    Q: How do I use MVC with LiveID ?
    A: Write your own Authorize filter. See http://forums.asp.net/t/1487782.aspx

  • Q: How do I fix the following error: "A potentially dangerous Request.Form value was detected from the client "
    A: See http://forums.asp.net/t/1487699.aspx

    Q: MVC App rendering in IE ok, but not in Firefox, Chrome, and Safari
    A: The Site.Master page's DOCTYPE was set to STRICT. I changed it to Transitional, and now the pages render the same in all browsers. See http://forums.asp.net/p/1484722/3489894.aspx

    Q: How do I check which event caused a post back?
    A: See http://forums.asp.net/t/1488333.aspx

    Q: How does MVC get indexed from search engines if the URL's are not file base?
    A: See http://forums.asp.net/t/1490362.aspx

    Q: How do I display data from my master page?
    A: You can use RenderAction from inside of a MasterPage. Just make an action and associated partial view for whatever it is you want to render in the Master Page. see http://forums.asp.net/t/1490283.aspx

    Q: How do I implement an Event Calendar in MVC?
    A: See http://web-matters.blogspot.com/2009/09/mvcjquery-calendar.html and http://forums.asp.net/t/1498976.aspx

    Q: How do I add tool tips to my menu items?
    A:  <%= Html.ActionLink("Home", "Index", "Home", new{title="My ToolTip"})%>  - also see http://forums.asp.net/t/1499223.aspx and http://flowplayer.org/tools/demos/tooltip/imitate.html

    Q: How do I get IIS to compress JSON?
    A: The httpCompression section can only be specified in applicationhost.config. You can set dynamic compression in IIS manager (you must have the dynamic content compression module installed. Under World WIde Web Services\Performance Features, select Http Compression Dynamic ). See http://forums.asp.net/p/1500145/3547024.aspx

    Q: parameters v. query strings.
    A: A URL is a resource.  MVC created Routing so that it more properly describes your site's resources, not so that you never have query strings in your applications.  As an example, parameters that affect the presentation but not the actual resource itself should generally be left as query strings rather than as route values. See http://forums.asp.net/t/1500133.aspx

    Q: How do I use the Ajax Controll Toolkit MaskEditBox in Asp.net mvc?
    A: http://forums.asp.net/t/1500954.aspx

    Q: How do HTTP modules work in MVC?
    A:ASP.NET MVC is still just ASP.NET under the hood, so the entire ASP.NET pipeline (including modules) still runs.  Things like authentication, output caching, and routing are all implemented as modules that run before the MVC pipeline executes.  So, yes, modules still work just as they always have, and you register them the same way. :)

    Q: I have two AJAX calls on one page and I expected them to run in concurrently but they run synchronously - why?
    A:  Because requests in MVC have access to session state, the requests are serialized to prevent corruption to session state. If you have long-running actions, you should make them async. It's about predictability rather than thread safety. If two requests for the same user, which both need read/write access to that user's session state, were allowed to run concurrently, then they could end up with session state being in an unpredictable state, because both requests are reading and writing to it. By serializing the requests per-user, this situation doesn't come into play.  When you use async action, then your request ends up with basically 3 phases: the beginning, where you schedule all the background work; the time when the background work is going on; and the end, when you collect all the results and formulate the response. The middle bit is where most of your time should be spent, and during that middle bit, the session is not locked, so concurrent connections from the same user will be allowed to execute while the work is going on in the background.See the article Using an Asynchronous Controller in ASP.NET MVC and blog entry Should my database calls be Asynchronous? See also http://forums.asp.net/t/1501623.aspx

    Q: How can I validate two properties matching (email, repeat email)?
    A: See http://forums.asp.net/t/1499238.aspx

    Validation

    Validation only ensures that the values that were edited are valid. If we ran validaiton on all properties, whether they were edited or not, it would break partial-editing scenarios.

    There are two ways to handle the radio button problem. The simpler one is to always ensure that at least one of the radio buttons was selected. The other way is to mimic what we do with check boxes: render an extra hidden input with the same name but a uniquely identifiable value. You'll need to write a special model binder to deal with the times where there are only one value (no radio button was selected) vs. two values (a radio button with selected). see http://forums.asp.net/p/1514750/3621789.aspx#3621789

    Q: Url.Action v. Html.ActionLink
    A: See http://forums.asp.net/t/1501042.aspx

    Q: How to capture xxx, 401 response in an global.asax app endRequest and change it to a yyy, 302.
    A: See http://forums.asp.net/t/1502740.aspx

    Q: How do I handle multiple submit buttons on one page or use use multple ActionResult into a single cotroller?
    A: See http://forums.asp.net/t/1502596.aspx

    Q:Connecting Htmlhelper with calendar control in mvc
    A: See http://forums.asp.net/t/1502517.aspx

    Q: How do I load an action from the master page?
    A: RenderAction

    Q: Hoe do I localize/globalize a MVC application?
    A: See http://oddiandeveloper.blogspot.com/2008/11/localization-with-aspnet-mvc.html

    Q: How can I do global error handling?
    A: See http://forums.asp.net/p/1505777/3579267.aspx

    Q:How do I fetch a subset of data using Entity Framework?
    A:See ASP.NET MVC Partial Views and Strongly Typed Custom ViewModels

    Q: How do I create a generic controller (one that takes a generic type like MyModel>?
    A: Create a base class that takes a generic type. See http://forums.asp.net/t/1475604.aspx

    Q: CakePHP style prefix routing with ASP.NET MVC 2
    A: See http://forums.asp.net/t/1517398.aspx

    Q:How do I get input-validation-error css set on textbox of nested object?
    A: See http://forums.asp.net/p/1514759/3625021.aspx

    JSON

  •  

    http://forums.asp.net/p/1529916/3701204.aspx

    http://forums.asp.net/t/1587366.aspx Nerd Diner JSON sample

  • Browsers will cache JSON just the same as they'll cache HTML, so make sure you're disabling browser caching in your JSON handlers.




    AREAS


  • Q: We have several AreaRegistration classes (derived from), and we are registering our  areas by calling AreaRegistration.RegisterAllAreas(); -- Is there a way to manage the order of this area registration?
    A: There is no built-in way to do this. However, by calling each area registration yourself you can decide the order. That is, instead of using RegisterAllAreas() you can have your own implementation that has either a hard-coded order of the areas or perhaps does some smarter look-up based on an attribute or property value.

    Q: How do I create one output assembly for each  Area or for each controller  (this for testing issues).
    A: There is no built-in way of doing this, but it’s certainly possible to do on your own in VS. All you need to do is create multiple projects in VS, one for each controller (or area or whatever). Then reference those projects from the main MVC web app project. You’ll have to make sure that you set up the right namespaces in each project so that the areas feature work because the area feature works based on namespaces of controllers.



  • TDD


  • Q:How do I mock HttpContext?
    A: Build a MVC project with unit tests and look at the account controller unit tests. See also http://forums.asp.net/p/1573848/3952560.aspx

    Q:We needed to have a common initialization done in our controllers. To accomplish this we have used a common base class and overridden there the “Initialize” method. The problem we are having is unit testing. In our unit tests we are creating our controllers by calling the constructor and then we set a test context for them and call their actions as member method. Following this pattern the “Initialize” method gets never executed. My question is how can we contruct/setup a controller so that it executes it’s Initialize method?
    A: This is a philosophical unit testing question. One school of thought is that the unit test should be testing only the action method being called and not depend on the Initialize method having been called. Thus the “unit” being tested is the action method and nothing else. This is the direction that many MVC TDD folks lean towards.
    The other school of thought says “whatever” and wants the Initialize method to be called. One aspect of this that can be a bit more complex is that you now might need to set up even more context objects to satisfy that method’s needs (though in yet other cases it may end up being simpler). In this case you can create a class that derives from your runtime controller, perhaps call it FooControllerHelper, and have that expose a new public method that can call in to protected Initialize method on the base class. Either approach can work, and each has its own caveats and limitations. In the end it’s up to you and your team to make the decision that makes the most sense for you (and your code).

    Q: How do I write a unit test in C# that will pass a mock (moq) System.Web.UI.Page object to a method call?
    A: You can abstract out the Page class using a hand-written IPage interface. The Page class is just not well designed for proper unit testing.

  • More on TDD

    Your unit tests are testing the controller, not the repository. Providing a fake repository and understanding your components interactions with other components is the correct way to write the test.

    Unit testing a component isn't necessarily just about input and output, but any interaction with the "outside world" (of which input and output are just one form). see http://forums.asp.net/p/1552636/3816827.aspx

    Simply executing a method during a unit test does just that - executes a method, and no more.  The MVC pipeline doesn't run, so binding and validation don't run.

    If you want to unit test your action's behavior for when ModelState is invalid, you need to manually make ModelState invalid.  You can use controller.ModelState.AddModelError("", "dummy error message") from within your unit test to force ModelState to be invalid.

  • Q: How do I test the combination of a controller action with a ActionFilter attribute (using OnActionExecuted to modify the ActionResult returned by the Action)?
    A: Test them separately.  You'd have a total of three tests: one that tests the logic of the action itself (without the filter), one that tests that the filter is applied to the action (via MethodInfo.GetAttributes(), presumably), and one that tests the filter logic itself (by calling OnActionExecuted() directly).  Since filters are cross-cutting, it's not really good practice to test action logic + filter logic within the same test. See also http://stackoverflow.com/questions/2118157/testing-an-mvc-controller-action-with-an-actionfilterattribute

    Q: My ModelState remains valid in Controller test even when it's not.
    A:Simply executing a method during a unit test does just that - executes a method, and no more.  The MVC pipeline doesn't run, so binding and validation don't run. If you want to unit test your action's behavior for when ModelState is invalid, you need to manually make ModelState invalid.  You can use controller.ModelState.AddModelError("", "dummy error message") from within your unit test to force ModelState to be invalid. see http://forums.asp.net/p/1529916/3926636.aspx

  • Performance

    Q: Why is may page rendering so slowly?
    A: You probably have Debug enabled. Make sure that you have debug = false in your web.config.
    <compilation debug="false" targetFramework="4.0">

    When debugging is on, we don't cache the mapping from view name to view file, because we assume that during development you will be adding/deleting views on a regular basis. This is made worse by the fact that, in MVC 2, we're calling an API that normally throws an exception when the view file isn't found, so a simple lookup of a template might cause several exceptions to be thrown. In MVC 3, we're using a new API in ASP.NET 4 which allows us to bypass this exception.
    Setting debug=true disables optimized code paths to assist in debugging.  In your particular case, it's disabling view location caching.  As a rule of thumb, always run with debug=false if you're running performance tests, as that will enable code path optimizations


  • Q: System.Web.Mvc.Html.ChildActionExtensions.RenderAction v. System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial  Performance
    A: RenderAction (slower) vs. RenderPartial (faster). RenderAction, by definition, has to run the whole ASP.NET pipeline to handle what appears to the system to be a new HTTP request, whereas RenderPartial is just adding extra content to an existing view.

    Q: I’m using [OutputCache(Location=OutputCacheLocation.Client, VaryByParam="id", Duration=3600)] for reading a message, it also cache's the username displayed on a page. ... and unfortunately, when I view a message that was meant for the entire class, it displays the username of the one who logged in first, not the currently logged on user.
    A: use [OutputCache(Duration=xxx, VaryByParam="id", VaryByHeader="Cookie")]

    Localization/CurrentCulture/UI

    Q: How do I set Thread CurrentCulture/Ui.
    A: set the culture from within Application_BeginRequest() (in Global.asax). For two additional approaches see http://forums.asp.net/p/1521130/3656712.aspx


  • Binding


    Q: I'm using ([Bind(exclude="Name")] in my action method, but Name is still validating?
    A: Validation is a separate step from binding.  [Bind] only controls which properties are set to user input values.  Validation in MVC 2 always takes place for all properties of the model, regardless if they have been set by user input.  See http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html for more information.

  • In your particular case, if you didn't intend for the Name property to be validated here, then remove the validation from it (remove [Required] or make the property type nullable).  Or change your model such that it doesn't have a Name property, since then the model more accurately describes the interaction you intended for the user to have with it.


    To change default validation messages & binding see http://forums.asp.net/p/1512140/3811684.aspx  (review entire thread)

    how do I disable required? see : If you want to disable this behavior entirely, then set DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValuesTypes to false during startup (in your Global.asax file).

    Q: I'm using Html.BeginForm, but my input control is always null, why?
    A:You're calling the wrong overload of BeginForm() - use the version that takes FormMethod.Post - see http://forums.asp.net/p/1570623/3935613.aspx
    Q: I want to move my Edit/Details templates to subfolders to clean up the directory structure. I want to have the following :

    /Employee
             Index.aspx
             /Edit       

                 Edit.aspx

                 EditPartial1.ascx

                 EditPartial2.ascx

    A: Use return View("Edit/Edit", employee);
    The only time you need to resort to fully qualified paths is if you want to break out of the default folder locations, but since everything is still under "~/Views/<controllername>", you're fine using the relative syntax. See http://forums.asp.net/p/1559881/3849308.aspx

    Q:  On a strong typed model I have a property of type IDictionary<int, string>. This is not used by the form ... only by a validation class after the form is submitted. However, since it isn't in the form when it is submitted its value are lost.
    A: See http://forums.asp.net/p/1522050/3661021.aspx


  • Model State and Validation
    (see Binding above for related info)

    Q: I have a bad user input ("PersonID") I need to correct and then validate, how do I do this?
    A: That’s usually a bad idea but you can call ModelState.Clear() before the call to UpdateModel, which will clear out all model state (values & errors). Or, if you just want to remove the errors for PersonID and not call the UpdateModel method the second time, you can call ModelState.Remove("PersonID"). See http://forums.asp.net/t/1502421.aspx

    Q: I have a custom model validator on a particular property. It shows the error at the top (in the Html.EnableClientValidation section). However, it does not show the message next to the field, even though I have a corresponding ValidationMessageFor
    A: See http://forums.asp.net/p/1521725/3659377.aspx

    UpdateModel() will set your model's properties to whatever was present in the form.  If your user typed a Shamsi-style date, that's what the OrderDate property will be set to.  What you can do is call UpdateModel() before your ShamsiToMiladi conversion function.  Or you can put a [Bind(Exclude = "OrderDate")] attribute on your model type, which signals to UpdateModel() that it should never set that property. see http://forums.asp.net/p/1553387/3814045.aspx

    Q: Why don't I get an error when I pass a string to a controller method that takes an Int32?
    A: The reason you don't get an exception is that model binding doesn't generally throw exceptions (unless you ask it to by calling UpdateModel on your controller). Model binding fails for the id parameter, so we pass null instead and set ModelState.IsValid to false. When id is an int, and therefore not nullable, we have to throw an error because there's no way to pass null for the id. see http://forums.asp.net/p/1553575/3816221.aspx

  • MVC JavaScript jQuery Links

    Trivia:

  • DisplayFor uses the HtmlEncode method, TextBoxFor uses  the HtmlAttributeEncode method - which converts only quotation marks ("), ampersands (&), and left angle brackets (<) to equivalent character entities. It is considerably faster than the HtmlEncode method.

  • How do I create a short name for a controller?  See http://forums.asp.net/p/1520690/3653961.aspx

  • Browsers will cache JSON just the same as they'll cache HTML, so make sure you're disabling browser caching in your JSON handlers.

    The way in which ASP.NET MVC uses Web Form pages for views is nothing more than an implementation detail. We’ve changed how those pages are executed a number of times already so any assumptions made regarding how those pages are run will probably become invalid before you know it (that is, putting code in the view). MVC supports multiple view engines.

    Q: I'm having problems with Sys_Mvc_FormContext$_form_OnSubmit -  submitButton.disableValidation is not supported in chrome as you cant access custom property on html elemtn this way. Should I use submitButton.getAttribute("disableValidation") instead.
    A: See http://forums.asp.net/p/1542586/3762960.aspx
    Q:AJAX.BeginForm and Html.ValidationSummary - How do I make an AJAX Form work correctly with Client Validation
    A: See http://forums.asp.net/p/1539076/3746727.aspx
    Q: Mvc2 Html Helpers does not render ID
    A: By design.  We changed the helpers in MVC 2 so that they don't output invalid IDs.  In HTML, an ID must begin with a letter.  This is why your GUID that starts with 'C' gets an ID auto-generated, but not your GUID that starts with the digit '9'. You can manually pass new { id = ... } as the htmlAttributes parameter of Html.TextBox() if you want to work around this.
    See http://forums.asp.net/p/1538128/3740697.aspx
    Q:MVC
    chat application problem with jQuery , JSON
    A: See http://forums.asp.net/p/1538519/3742982.aspx
    Q:Whats the story on NerdDinner and MVC 2?
    A: See http://forums.asp.net/p/1536452/3737358.aspx
    Q: How do  ASP.NET MVC Sessions across subdomains work
    A:  see http://forums.asp.net/t/1539379.aspx
    Q: Where should I call DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter)); 
    A: This should go in Application_Start, not the EmailAttribute static constructor. see http://forums.asp.net/p/1539076/3746841.aspx
    Q: How do I get my  AJAX Form work correctly with Client Validation?
    A: See http://forums.asp.net/p/1539076/3746841.aspx
    Q: I can't get cookie-less session working with MVC,
    A: This isn't something the framework handles automatically for you, and cookieless sessions aren't designed for this scenario.  You can use hidden inputs to keep track of state, the Html.Serialize() helper from Futures, or WebForms + ViewState.  What all of these suggestions have in common is that they move the state you're trying to store out of Session and to the actual pages themselves.cookie-less session were designed to support mobile devices which didn't support cookies, and such devices have now probably all disappeared.The scenarios for supporting cookieless sessions are rapidly dwindling,cookieless sessions are not supported in ASP.NET MVC (only in WebForms), and it's likely that we will never support cookieless sessions in MVC. See http://forums.asp.net/p/1517391/3746540.aspx
    Q:How do I Internationalize DataAnnotations error messages using a custom  SQL resource provider
    A:http://forums.asp.net/p/1537591/3738421.aspx
    Q: MVC 2 futures: FormExtensions make wrong paths when adding area to site
    A: See http://forums.asp.net/p/1535698/3730848.aspx
    Q: Model validation happens automatically with DateTime fields, but not other NOT NULL fields
    A:  See http://forums.asp.net/t/1536171.aspx
    Q: How to implement multiple synchronization points on Controller async action.
    A: See http://forums.asp.net/p/1531002/3722202.aspx
    Q: How do I validate a complex object that is a composite of multiple fields ( for example  person.FullName = String.Format("{0} {1}", person.Name, person.Surname);   )
    A: see http://forums.asp.net/p/1535155/3726647.aspx
    Note: the above would make a great blog
    Q: I'm using a Custom ErrorMessage for DataAnnotations.DataTypeAttribute but I don't get the custom error message:
    A: DataTypeAttribute is a little confusing, because it allows you to write your own validation but doesn't come with any built-in, so setting ErrorMessage and friends doesn't actually do anything until you add your own validation code.  see http://forums.asp.net/p/1533748/3721895.asp

    Q: Button Onclick event (which is in codbehind) doesn’t get triggered in MVC 2
    A:  see http://stackoverflow.com/questions/2767819/button-onclick-event-which-is-in-codbehind-doesnt-get-triggered-in-mvc-2.
    Q: How do I bind a bool value to a checkbox in MVC 2?
    A: see http://forums.asp.net/p/1556189/3826935.aspx
    Q: How do I bind a method to a viewengine at runtime?
    A:If you have an instance of a ViewResult, you can specify which view engines will be used when executing that result.  Set the ViewResult.ViewEngines property (it's setter is public) to contain the list of all the view engines you want queried for this particular ViewResult.  If you know ahead of time that a particular view engine should be used, just create a new ViewEngineCollection and give it a single entry containing the view engine you want to use.

    Q: Is URL rewriting really needed?

    A: A scenario that URL Rewriting solves nicely is that of multiple subdomains being routed to a single machine.  For example, the IIS URL Rewriting module can be used to have your browser display http://app1.example.com/ or http://app2.example.com/, and the server will treat it as a request for http://content.example.com/app1/ or http://content.example.com/app2/.  This is much, much easier to pull off with IIS URL Rewriting than with ASP.NET Routing. see also http://forums.asp.net/p/1554085/3816861.aspx    and http://forums.asp.net/p/1547663/3788358.aspx

    Q: What's a fast way to copy a model?
    A: See http://forums.asp.net/p/1553997/3816694.aspx

  • Misc good blogs

    Misc good Posts

    Technorati Tags: