예제 #1
0
        //model绑定适用于带 ? 属性的实体
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object obj = new DefaultModelBinder().BindModel(controllerContext, bindingContext);

            //   object obj = Activator.CreateInstance(bindingContext.ModelType);
            foreach (PropertyInfo p in bindingContext.ModelType.GetProperties())
            {
                //ValueProviderResult vpResult=  bindingContext.ValueProvider.GetValue(p.Name);
                var    customAttr   = p.GetCustomAttribute(typeof(PropertyModelBinderAttribute));
                string propertyName = customAttr != null ? ((PropertyModelBinderAttribute)customAttr).PropertyName : p.Name;

                if (p.PropertyType.Name.StartsWith("Nullable") || customAttr != null)
                {
                    //忽略表单安全(不严重参数代码)
                    var valueProvider            = (bindingContext.ValueProvider as IUnvalidatedValueProvider);
                    ValueProviderResult vpResult = valueProvider.GetValue(propertyName, true);
                    if (vpResult != null)
                    {
                        object value = vpResult.ConvertTo(p.PropertyType);
                        p.SetValue(obj, value, null);
                    }
                }
            }

            return(obj);
        }
예제 #2
0
        private ToDoController CreateToDoController(object ViewModel = null, bool isAuthorized = true)
        {
            MockingHelper.InitMocking();
            ToDoController toDoController;

            if (isAuthorized)
            {
                toDoController = new ToDoController(MockingHelper.DBContext, MockingHelper.ApplicationManager);
            }
            else
            {
                var userStore = new Mock <IUserStore <ApplicationUser> >();
                var applicationUserManager = new Mock <UserManager <ApplicationUser> >(userStore.Object);
                toDoController = new ToDoController(MockingHelper.DBContext, applicationUserManager.Object);
            }

            toDoController.ControllerContext = MockingHelper.ControllerContext;
            if (ViewModel != null)
            {
                var modelBinder = new System.Web.Mvc.ModelBindingContext()
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => ViewModel, ViewModel.GetType()),
                    ValueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), CultureInfo.InvariantCulture)
                };
                var binder = new DefaultModelBinder().BindModel(toDoController.ControllerContext, modelBinder);
                toDoController.ModelState.Clear();
                toDoController.ModelState.Merge(modelBinder.ModelState);
            }
            return(toDoController);
        }
예제 #3
0
        public void NoEmailFilledIn()
        {
            //Arange
            LoginController loginController = new LoginController();
            Login           loginAttempt    = new Login();

            loginAttempt.emailAddress = "";
            loginAttempt.password     = "******";
            var modelBinder = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                    () => loginAttempt, loginAttempt.GetType()),
                ValueProvider = new NameValueCollectionValueProvider(
                    new NameValueCollection(), CultureInfo.InvariantCulture)
            };

            var binder = new DefaultModelBinder().BindModel(
                new ControllerContext(), modelBinder);

            loginController.ModelState.Clear();
            loginController.ModelState.Merge(modelBinder.ModelState);

            //Act
            ViewResult result = (ViewResult)loginController.Login(loginAttempt);

            //Assert
            Assert.IsTrue(!result.ViewData.ModelState.IsValid);
            Assert.AreEqual(result.ViewData.ModelState["emailAddress"].Errors[0].ErrorMessage, "Er is geen e-mailadres ingevuld");
        }
예제 #4
0
        public override object GetControlFormValue(Controller controller, WorkContext workContext)
        {
            var model = new List <MediaPart>();

            var binder         = new DefaultModelBinder();
            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
                ModelState    = controller.ViewData.ModelState,
                ValueProvider = controller.ValueProvider,
                ModelName     = Name
            };

            binder.BindModel(controller.ControllerContext, bindingContext);

            // Move media files to correct folder
            if (model.Count > 0)
            {
                var mediaService = workContext.Resolve <IMediaService>();
                mediaService.MoveFiles(model, PhotosFolder);
            }

            model.Sort((x, y) => x.SortOrder.CompareTo(y.SortOrder));

            return(model);
        }
예제 #5
0
        protected object Bind(string parameterName, Type parameterType, object parameters)
        {
            var modelBinder = new DefaultModelBinder();
            var result      = modelBinder.BindModel(RequestBuilder.CreateRequest().BuildRequest(), new ModelBindingContext("foo", MethodBase.GetCurrentMethod() as MethodInfo, parameterType, new RouteValueDictionary(parameters)));

            return(result);
        }
예제 #6
0
        public void CreateSessionWithInvalidModel_ShouldReturnModelStateNotValid()
        {
            var controller = new SessionController(_activityManager, _sessionManager, _personManager, _utilityManager);

            var model = new CreateSessionViewModel()
            {
                Activity = null,
                Name     = ""
            };

            //Init ModelState
            var modelBinder = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                    () => model, model.GetType()),
                ValueProvider = new NameValueCollectionValueProvider(
                    new NameValueCollection(), CultureInfo.InvariantCulture)
            };
            var binder = new DefaultModelBinder().BindModel(
                new ControllerContext(), modelBinder);

            controller.ModelState.Clear();
            controller.ModelState.Merge(modelBinder.ModelState);

            ViewResult result = (ViewResult)controller.CreateSession(model);

            Assert.IsTrue(result.ViewData.ModelState["Activity"].Errors.Count > 0);
            Assert.IsTrue(result.ViewData.ModelState["Name"].Errors.Count > 0);
            Assert.IsTrue(!result.ViewData.ModelState.IsValid);
        }
        public void BindingFilterOptions()
        {
            var formCollection = new NameValueCollection
            {
                { "foo.LoadFilterId", "10" },
                { "foo.FilterType", "FilterType.Fast" },

                { "foo.Filters[filter1].Values", "10" },
                { "foo.Filters[filter1].ConditionKey", "equal" },
                { "foo.Filters[filter1].TypeName", typeof(Int32).FullName },

                { "foo.Filters[filter2].LeftValue", "2345.14" },
                { "foo.Filters[filter2].ConditionKey", "equal" },
                { "foo.Filters[filter2].TypeName", typeof(Decimal).FullName },

                { "foo.Filters[filter3].LeftValue", "testname" },
                { "foo.Filters[filter3].ConditionKey", "equal" },
                { "foo.Filters[filter3].TypeName", typeof(string).FullName }
            };

            var modelBinder = new DefaultModelBinder();

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);

            var bindingContext = new ModelBindingContext
            {
                ModelName     = "foo",
                ValueProvider = valueProvider,
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(FilterOptions)),
            };

            var controllerContext = new ControllerContext();

            var filterOptions = modelBinder.BindModel(controllerContext, bindingContext) as IFilterOptions;

            Assert.IsNotNull(filterOptions);

            Assert.IsTrue(filterOptions.Filters.Any());

            Assert.IsTrue(filterOptions.Filters.ContainsKey("filter1"));
            var filter1 = filterOptions.Filters["filter1"] as IFilterValue <int?>;

            Assert.IsNotNull(filter1);
            Assert.IsTrue(filter1.Values.Contains(10));
            Assert.IsTrue(filter1.ConditionKey == "equal");

            Assert.IsTrue(filterOptions.Filters.ContainsKey("filter2"));
            var filter2 = filterOptions.Filters["filter2"] as IFilterValue <decimal?>;

            Assert.IsNotNull(filter2);
            Assert.IsTrue(filter2.LeftValue == 2345.14M);
            Assert.IsTrue(filter2.ConditionKey == "equal");

            Assert.IsTrue(filterOptions.Filters.ContainsKey("filter3"));
            var filter3 = filterOptions.Filters["filter3"] as IFilterValue <string>;

            Assert.IsNotNull(filter3);
            Assert.IsTrue(filter3.LeftValue == "testname");
            Assert.IsTrue(filter3.ConditionKey == "equal");
        }
예제 #8
0
        public void Create_InvalidModel_ReturnsViewWithModel()
        {
            // Arrange
            var movieToCreate = new Movie();
            var modelBinder   = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                    () => movieToCreate, movieToCreate.GetType()),
                ValueProvider = new NameValueCollectionValueProvider(
                    new NameValueCollection(), CultureInfo.InvariantCulture)
            };
            var binder = new DefaultModelBinder().BindModel(
                new ControllerContext(), modelBinder);

            _controller.ModelState.Clear();
            _controller.ModelState.Merge(modelBinder.ModelState);

            // Act
            var result = _controller.Create(movieToCreate) as ViewResult;

            // Assert
            Assert.IsTrue(result.ViewData.ModelState["Genre"].Errors.Count > 0);
            Assert.IsTrue(result.ViewData.ModelState["Price"].Errors.Count > 0);
            Assert.IsFalse(result.ViewData.ModelState.IsValid);
        }
예제 #9
0
        public static IEnumerable <TextContent> GetCategories(string modelName, ControllerContext controllerContext, NameValueCollection formValues)
        {
            var modelState = new ModelStateDictionary();
            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                FallbackToEmptyPrefix = true,
                ModelMetadata         = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(CategoryContent[])),
                ModelName             = modelName,
                ModelState            = modelState,
                ValueProvider         = new ValueProviderCollection(new List <System.Web.Mvc.IValueProvider>()
                {
                    new NameValueCollectionValueProvider(formValues, formValues, CultureInfo.CurrentCulture), controllerContext.Controller.ValueProvider
                })
            };
            DefaultModelBinder modelBinder = new DefaultModelBinder();
            var model = modelBinder.BindModel(controllerContext, bindingContext);

            if (model == null)
            {
                return(null);
            }
            return(((IEnumerable <CategoryContent>)model).Select(it => new TextContent()
            {
                FolderName = it.FolderName, UUID = it.UUID
            }));
        }
        public void ShouldProcessTheDefaultValidatorForNotNullableValueTypesWhenFormValueIsNull()
        {
            ControllerContext controllerContext = new ControllerContext {
                HttpContext = Substitute.For <HttpContextBase>()
            };
            IValidatorFactory validatorFactory = Substitute.For <IValidatorFactory>();

            validatorFactory.GetValidatorForOptional(typeof(TestModel)).Returns(x => new TestModelValidator());

            LaboModelValidatorProvider.Configure(validatorFactory);

            FormCollection form = new FormCollection
            {
                { "Age", string.Empty }
            };

            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelName             = "test",
                ModelMetadata         = GetModelMetaData(typeof(TestModel)),
                ModelState            = new ModelStateDictionary(),
                FallbackToEmptyPrefix = true,
                ValueProvider         = form.ToValueProvider()
            };

            DefaultModelBinder binder = new DefaultModelBinder();

            binder.BindModel(controllerContext, bindingContext);

            Assert.AreEqual("'Age' must not be empty.", bindingContext.ModelState["Age"].Errors.Single().ErrorMessage);
        }
예제 #11
0
    /// <summary>
    /// Method to get model from QueryString
    /// </summary>
    /// <param name="request">HttpRequest</param>
    /// <returns>T model</returns>
    public static T GetModelFromQueryString(HttpRequest request)
    {
        modelBindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T));
        modelBindingContext.ValueProvider = new NameValueCollectionValueProvider(request.QueryString, System.Globalization.CultureInfo.InvariantCulture);
        IModelBinder mb = new DefaultModelBinder();

        return((T)mb.BindModel(new ControllerContext(), modelBindingContext));
    }
        public void Model_Validation_For_Required_Field_Missing_Fails()
        {
            var model  = new Fakes.FakeHomeViewModel();
            var values = new NameValueCollection();
            var binder = new DefaultModelBinder(model, values);

            binder.Bind();
            Assert.IsTrue(binder.ModelState.HasErrors);
        }
예제 #13
0
        public void Init_And_BuildExpression()
        {
            var formCollection = new NameValueCollection
            {
                { "Filters[CategoryId].Values", "1" },
                { "Filters[CategoryId].Values", "14" },
                { "Filters[CategoryId].Values", "5" },
                { "Filters[CategoryId].ConditionKey", "isin" },
                { "Filters[CategoryId].TypeName", typeof(Int32).FullName },

                { "Filters[UnitPrice].LeftValue", "10" },
                { "Filters[UnitPrice].RightValue", "2345.14" },
                { "Filters[UnitPrice].ConditionKey", "between" },
                { "Filters[UnitPrice].TypeName", typeof(Decimal).FullName },

                { "Filters[Name].LeftValue", "testname" },
                { "Filters[Name].ConditionKey", "contains" },
                { "Filters[Name].TypeName", typeof(string).FullName }
            };

            var modelBinder = new DefaultModelBinder();

            var valueProvider = new NameValueCollectionValueProvider(formCollection, null);

            var bindingContext = new ModelBindingContext
            {
                ModelName     = string.Empty,
                ValueProvider = valueProvider,
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(FilterOptions)),
            };

            var controllerContext = new ControllerContext();

            var filterOptions = modelBinder.BindModel(controllerContext, bindingContext) as IFilterOptions;

            Assert.IsNotNull(filterOptions);

            var productFilter = new ProductFilter().Init(filterOptions);

            var expression = productFilter.BuildExpression <Product>();

            Assert.IsNotNull(expression);

            var predicat = expression.Compile();

            Assert.IsFalse(predicat(new Product {
                CategoryId = 24444, Name = string.Empty
            }));

            Assert.IsTrue(predicat(new Product
            {
                Name       = "testname",
                CategoryId = 14,
                UnitPrice  = 23,
            }));
        }
예제 #14
0
 public void SetUp()
 {
     binder            = new DefaultModelBinder();
     controllerContext = new ControllerContext
     {
         HttpContext = MockRepository.GenerateStub <HttpContextBase>()
     };
     request = MockRepository.GenerateStub <HttpRequestBase>();
     controllerContext.HttpContext.Stub(x => x.Request).Return(request);
 }
예제 #15
0
 public ModelBinderTester()
 {
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
     provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());
     ModelValidatorProviders.Providers.Add(provider);
     DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
     binder            = new DefaultModelBinder();
     controllerContext = new ControllerContext {
         HttpContext = MockHttpContext.Create()
     };
 }
        public void Model_Validation_For_Range_Check_Passes()
        {
            var model = new Fakes.FakeHomeViewModel()
            {
                HelloWorld = "Hello Mvc!", CreatedDate = "11/1/2010", SomeInt = 1
            };
            var values = new NameValueCollection();
            var binder = new DefaultModelBinder(model, values);

            binder.Bind();
            Assert.IsFalse(binder.ModelState.HasErrors);
        }
예제 #17
0
        private static void TryUpdateModel(ISettings model, ControllerContext controllerContext)
        {
            var binder         = new DefaultModelBinder();
            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
                ModelState    = controllerContext.Controller.ViewData.ModelState,
                ValueProvider = controllerContext.Controller.ValueProvider
            };

            binder.BindModel(controllerContext, bindingContext);
        }
예제 #18
0
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     if (bindingContext.ModelType.IsInterface || bindingContext.ModelType.IsAbstract)
     {
         return(Easy.Reflection.ClassAction.GetModel(ServiceLocator.Current.GetInstance(bindingContext.ModelType).GetType(), controllerContext.RequestContext.HttpContext.Request.Form));
     }
     else
     {
         DefaultModelBinder binder = new DefaultModelBinder();
         return(binder.BindModel(controllerContext, bindingContext));
     }
 }
예제 #19
0
        public T TryGetModel <T>(string key) where T : class
        {
            var binder            = new DefaultModelBinder();
            var controllerContext = new ControllerContext();
            var context           = new ModelBindingContext {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(T)),
                ModelName     = key,
                ValueProvider = this.ToValueProvider(null)
            };

            return((T)binder.BindModel(controllerContext, context));
        }
        public void Model_Validation_For_Regular_Expression_Check_Fails()
        {
            var model = new Fakes.FakeHomeViewModel()
            {
                HelloWorld = "Hello Mvc!", CreatedDate = "11/1/2"
            };
            var values = new NameValueCollection();
            var binder = new DefaultModelBinder(model, values);

            binder.Bind();
            Assert.IsTrue(binder.ModelState.HasErrors);
        }
예제 #21
0
        protected void TryUpdateModel(object model, Type modelType, IValueProvider valueProvider = null)
        {
            var binder         = new DefaultModelBinder();
            var bindingContext = new ModelBindingContext
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType),
                ModelState    = ViewData.ModelState,
                ValueProvider = valueProvider ?? ValueProvider //provider
            };

            binder.BindModel(ControllerContext, bindingContext);
        }
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var modelBinder = new DefaultModelBinder();
        var movie       = modelBinder.BindModel(controllerContext, bindingContext) as Movie;
        var id          = controllerContext.HttpContext.Request.Form["Id"];

        if (movie != null)
        {
            movie.Id = new ObjectId(id);
            return(movie);
        }
        return(null);
    }
예제 #23
0
        public DefaultModelBinderTests()
        {
            var services = new ServiceCollection();

            services.ConfigureOptions <JsonConfigureOptions>();
            services.AddVoyager(c => c.AddAssemblyWith <BlankPolicy>());
            provider    = services.BuildServiceProvider();
            binder      = provider.GetService <DefaultModelBinder>();
            httpContext = new DefaultHttpContext
            {
                RequestServices = services.BuildServiceProvider(),
            };
        }
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var modelBindingContext = new ModelBindingContext
        {
            ModelName     = bindingContext.ModelName,
            ModelMetadata = new ModelMetadata(new EmptyModelMetadataProvider(), null,
                                              null, typeof(Dictionary <TKey, TValue>), bindingContext.ModelName),
            ValueProvider = new QueryStringValueProvider(controllerContext)
        };
        var temp = new DefaultModelBinder().BindModel(controllerContext, modelBindingContext);

        return(temp);
    }
예제 #25
0
        public static object Parse(this FormCollection formCollection, ControllerContext controllerContext, Type configurationType, string prefix, bool useEmptyPrefix = false)
        {
            var metadataForType     = ModelMetadataProviders.Current.GetMetadataForType(null, configurationType);
            var modelBindingContext = new ModelBindingContext
            {
                ModelName             = prefix,
                ModelMetadata         = metadataForType,
                ValueProvider         = formCollection.ToValueProvider(),
                FallbackToEmptyPrefix = useEmptyPrefix
            };
            var binder = new DefaultModelBinder().BindModel(controllerContext, modelBindingContext);

            return(binder);
        }
예제 #26
0
            public static void SetupControllerModelState <T>(T model, Controller controller)
            {
                var modelBinder = new ModelBindingContext
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
                    ValueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), CultureInfo.InvariantCulture)
                };

                var binder = new DefaultModelBinder();

                binder.BindModel(new ControllerContext(), modelBinder);
                controller.ModelState.Clear();
                controller.ModelState.Merge(modelBinder.ModelState);
            }
        public void Bind_Model_From_Request_Form_Values_Success()
        {
            var model  = new Fakes.FakeHomeViewModel();
            var values = new NameValueCollection();

            values.Add("HelloWorld", "Hello Mvc!");

            var binder = new DefaultModelBinder(model, values);

            binder.Bind();

            Assert.IsFalse(binder.ModelState.HasErrors);
            Assert.AreEqual("Hello Mvc!", model.HelloWorld);
        }
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var dmb    = new DefaultModelBinder();
        var result = dmb.BindModel(controllerContext, bindingContext);
        // ^^ result == null
        var rawValueAsChar = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ConvertTo(typeof(char));
        // ^^ rawValueAsChar == null
        var rawValueAsString = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;

        if (!string.IsNullOrEmpty(rawValueAsString))
        {
            return(rawValueAsString.ToCharArray()[0]);
        }
        return(null);
    }
예제 #29
0
        private void SetModelState(Controller controller, object ob)
        {
            var modelBinder = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                    () => ob, ob.GetType()),
                ValueProvider = new NameValueCollectionValueProvider(
                    new NameValueCollection(), CultureInfo.InvariantCulture)
            };
            var binder = new DefaultModelBinder().BindModel(
                new ControllerContext(), modelBinder);

            controller.ModelState.Clear();
            controller.ModelState.Merge(modelBinder.ModelState);
        }
예제 #30
0
        ///////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////

        public WorkflowManager(
            W workflow,
            DefaultModelBinder dmb,
            Action <ValidationError> addValidationError,
            ViewDataDictionary viewData,
            TempDataDictionary tempData = null
            )
            : this(workflow, new ContextInfo()
        {
            DefaultModelBinder = dmb,
            AddValidationError = addValidationError,
            ViewData = viewData,
            TempData = tempData
        })
        {
            ;
        }