2010-06-21 Marek Habersack <mhabersack@novell.com>
[mcs.git] / class / System.Web.Mvc / System.Web.Mvc / ModelBinders.cs
blobb8aa238acb741ddd49707a798e0e36be0e1739ec
1 /* ****************************************************************************
3 * Copyright (c) Microsoft Corporation. All rights reserved.
5 * This software is subject to the Microsoft Public License (Ms-PL).
6 * A copy of the license can be found in the license.htm file included
7 * in this distribution.
9 * You must not remove this notice, or any other, from this software.
11 * ***************************************************************************/
13 namespace System.Web.Mvc {
14 using System;
15 using System.Reflection;
16 using System.Web;
18 public static class ModelBinders {
20 private static readonly ModelBinderDictionary _binders = CreateDefaultBinderDictionary();
22 public static ModelBinderDictionary Binders {
23 get {
24 return _binders;
28 internal static IModelBinder GetBinderFromAttributes(ICustomAttributeProvider element, Func<string> errorMessageAccessor) {
29 // this method is used to get a custom binder based on the attributes of the element passed to it.
30 // it will return null if a binder cannot be detected based on the attributes alone.
32 CustomModelBinderAttribute[] attrs = (CustomModelBinderAttribute[])element.GetCustomAttributes(typeof(CustomModelBinderAttribute), true /* inherit */);
33 if (attrs == null) {
34 return null;
37 switch (attrs.Length) {
38 case 0:
39 return null;
41 case 1:
42 IModelBinder binder = attrs[0].GetBinder();
43 return binder;
45 default:
46 string errorMessage = errorMessageAccessor();
47 throw new InvalidOperationException(errorMessage);
51 private static ModelBinderDictionary CreateDefaultBinderDictionary() {
52 // We can't add a binder to the HttpPostedFileBase type as an attribute, so we'll just
53 // prepopulate the dictionary as a convenience to users.
55 ModelBinderDictionary binders = new ModelBinderDictionary() {
56 { typeof(HttpPostedFileBase), new HttpPostedFileBaseModelBinder() }
58 return binders;