Ejemplo n.º 1
0
        private async Task <T> BindFormDataToModelAsync <T>(FormValueProvider formValueProvider) where T : class, new()
        {
            var data = new T();
            var bindingSuccessful = await TryUpdateModelAsync(data, prefix : "", valueProvider : formValueProvider);

            return(data);
        }
        protected virtual async Task <bool> BindDataAsync(SubmissionData model, Dictionary <string, StringValues> dataToBind)
        {
            var formValueProvider = new FormValueProvider(BindingSource.Form, new FormCollection(dataToBind), CultureInfo.CurrentCulture);
            var bindingSuccessful = await TryUpdateModelAsync(model, "", formValueProvider);

            return(bindingSuccessful);
        }
        public async Task ShouldBindDateTimeAsModel(int?year, int?month, int?day, bool isValid)
        {
            var formCollection = new FormCollection(new Dictionary <string, StringValues>()
            {
                { "Day", day.ToString() },
                { "Month", month.ToString() },
                { "Year", year.ToString() },
            });

            var binder = new DateTimeModelBinder();

            var vp = new FormValueProvider(BindingSource.Form, formCollection, CultureInfo.CurrentCulture);

            var context = GetBindingContext(vp, typeof(DateTime));

            await binder.BindModelAsync(context);

            context.ModelState.IsValid.Should().Be(isValid);

            if (isValid)
            {
                var dateValue = (DateTime)context.Result.Model;

                dateValue.Date.Day.Should().Be(day);
                dateValue.Date.Month.Should().Be(month);
                dateValue.Date.Year.Should().Be(year);
                dateValue.TimeOfDay.Hours.Should().Be(0);
                dateValue.TimeOfDay.Minutes.Should().Be(0);
                dateValue.TimeOfDay.Seconds.Should().Be(0);
            }
            else
            {
                context.ModelState.ErrorCount.Should().Be(1);
            }
        }
        public async Task ShouldBindDateTimeAsModel(string?year, string?month, bool isValid, string expectedDateString)
        {
            var formCollection = new FormCollection(new Dictionary <string, StringValues>()
            {
                { "Month", month?.ToString() },
                { "Year", year?.ToString() },
            });

            var binder = new DateMonthYearModelBinder();

            var vp = new FormValueProvider(BindingSource.Form, formCollection, CultureInfo.CurrentCulture);

            var context = GetBindingContext(vp, typeof(string));

            await binder.BindModelAsync(context);

            context.ModelState.IsValid.Should().Be(isValid);

            if (isValid)
            {
                var dateValueString = (string)context.Result.Model;

                dateValueString.Should().Be(expectedDateString);
            }
            else
            {
                context.ModelState.ErrorCount.Should().Be(1);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 获取提交的所有参数
        /// </summary>
        /// <param name="ivp"></param>
        /// <returns></returns>
        string GetAllParam(IValueProvider ivp)
        {
            Dictionary <string, string> Qsvp = new Dictionary <string, string>();
            Dictionary <string, string> Fvp  = new Dictionary <string, string>();
            ValueProviderCollection     vp   = (ValueProviderCollection)ivp;

            foreach (var v in vp)
            {
                Type t = v.GetType();
                if (t.ToString() == "System.Web.Mvc.QueryStringValueProvider")
                {
                    QueryStringValueProvider qvp = (QueryStringValueProvider)v;
                    foreach (var keys in qvp.GetKeysFromPrefix(""))
                    {
                        Qsvp.Add(keys.Key, qvp.GetValue(keys.Key).AttemptedValue);
                    }
                }
                if (t.ToString() == "System.Web.Mvc.FormValueProvider")
                {
                    FormValueProvider qvp = (FormValueProvider)v;
                    foreach (var keys in qvp.GetKeysFromPrefix(""))
                    {
                        Fvp.Add(keys.Key, qvp.GetValue(keys.Key).AttemptedValue);
                    }
                }
            }
            var param = new
            {
                QueryString = Qsvp,
                FormValue   = Fvp
            };

            return(Newtonsoft.Json.JsonConvert.SerializeObject(param));
        }
Ejemplo n.º 6
0
        protected Person GetPerson()
        {
            Person         model    = new Person();
            IValueProvider provider = new FormValueProvider(ModelBindingExecutionContext);

            TryUpdateModel <Person>(model, provider);
            return(model);
            //String nameFormValue = Request.Form["name"];
            //if (String.IsNullOrEmpty(nameFormValue))
            //{
            //    throw new FormatException("Please provide your name");
            //}
            //else if (nameFormValue.Length < 3 || nameFormValue.Length > 20)
            //{
            //    throw new FormatException("Your name must be 3-20 characters");
            //}
            //else if (!Regex.IsMatch(nameFormValue, @"^[A-Za-z\s]+$"))
            //{
            //    throw new FormatException("Your name can only contain letters and spaces");
            //}
            //else
            //{
            //    model.Name = Request.Form["name"];
            //}
            //model.Age = Int32.Parse(Request.Form["age"]);
            //model.Cell = Request.Form["cell"];
            //model.Zip = Request.Form["zip"];
            //return model;
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Upload()
        {
            var list = 0;
            //FormValueProvider formModel = await Request.StreamFiles(@"D:\Users\INEREST\source\repos\TJCU.CKSP\TJCU.CKSP\UploadingFiles");
            FormValueProvider formModel = await Request.StreamFiles(host.WebRootPath + @"\UploadingFiles");

            //formModel = await Request.StreamFiles(@"D:\Users\INEREST\source\repos\TJCU.CKSP\TJCU.CKSP\UploadingFiles\"+file.CourseId.ToString());
            var viewModel = new MyViewModel();

            var bindingSuccessful = await TryUpdateModelAsync(viewModel, prefix : "", valueProvider : formModel);

            if (!bindingSuccessful)
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
            }
            else
            {
            }
            //return View();
            return(Ok(new { code = 400, msg = "上传文件成功!" }));
            //return Ok(viewModel);
        }
Ejemplo n.º 8
0
    private static async Task AddValueProviderAsync(ValueProviderFactoryContext context)
    {
        var             request = context.ActionContext.HttpContext.Request;
        IFormCollection form;

        try
        {
            form = await request.ReadFormAsync();
        }
        catch (InvalidDataException ex)
        {
            // ReadFormAsync can throw InvalidDataException if the form content is malformed.
            // Wrap it in a ValueProviderException that the CompositeValueProvider special cases.
            throw new ValueProviderException(Resources.FormatFailedToReadRequestForm(ex.Message), ex);
        }
        catch (IOException ex)
        {
            // ReadFormAsync can throw IOException if the client disconnects.
            // Wrap it in a ValueProviderException that the CompositeValueProvider special cases.
            throw new ValueProviderException(Resources.FormatFailedToReadRequestForm(ex.Message), ex);
        }

        var valueProvider = new FormValueProvider(
            BindingSource.Form,
            form,
            CultureInfo.CurrentCulture);

        context.ValueProviders.Add(valueProvider);
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                Component component = new Component();

                // Получить данные из формы с помощью средств
                // привязки моделей ASP.NET
                IValueProvider provider =
                    new FormValueProvider(ModelBindingExecutionContext);
                if (TryUpdateModel <Component>(component, provider))
                {
                    // В этой точке непосредственно начинается работа с Entity Framework

                    // Создать объект контекста
                    EFDbContext context = new EFDbContext();

                    // Вставить данные в таблицу Customers с помощью LINQ
                    context.Components.Add(component);

                    // Сохранить изменения в БД
                    context.SaveChanges();
                }
            }
        }
        public ActionResult FixValueProviderPost()
        {
            //Value provider csak az URL paraméterrel dolgozik
            var querystringValues = new QueryStringValueProvider(this.ControllerContext);
            var routeValues       = new RouteDataValueProvider(this.ControllerContext);

            ValueProviderResult action     = querystringValues.GetValue("action");      //action=null
            ValueProviderResult controller = querystringValues.GetValue("controller");  //controller=null

            ValueProviderResult idResult = querystringValues.GetValue("Id");            //idResult=null

            int    id         = (int)routeValues.GetValue("Id").ConvertTo(typeof(int)); //idResult=99999
            string EzNemValid = querystringValues.GetValue(key: "WillNeverValid").AttemptedValue;

            var model = CategoryModel.GetCategory(1);

            //A model.WillNeverValid értéke "Hát ez honnan jött?" lesz:
            this.TryUpdateModel <CategoryModel>(model, string.Empty, querystringValues);

            //Input mezők
            var  formValues = new FormValueProvider(this.ControllerContext);
            bool szerepel   = formValues.ContainsPrefix("prefix.WillNeverValid");

            this.TryUpdateModel <CategoryModel>(model, "prefix", formValues);

            return(RedirectToAction("FixValueProvider"));
        }
        private async Task AddValueProviderAsync(ValueProviderFactoryContext context)
        {
            var             request = context.ActionContext.HttpContext.Request;
            IFormCollection form;

            try
            {
                request.Body.Position = 0;
                var body = await request.BodyReader.ReadAsync();

                var CiphertextArray = MessagePackSerializer.Deserialize <byte[][]>(body.Buffer, MessagePack.Resolvers.ContractlessStandardResolver.Options);
                var plainText       = new StringBuilder();

                for (int i = 0; i < CiphertextArray.Length; i++)
                {
                    plainText.Append(_certificate.DecryptFromUTF8bytes(CiphertextArray[i]));
                }
                var formReader = new FormReader(plainText.ToString());
                var formFields = await formReader.ReadFormAsync();

                form = new FormCollection(formFields);
            }
            catch (Exception)
            {
                throw;
                //throw new ValueProviderException(Resources.FormatFailedToReadRequestForm(ex.Message), ex);
            }

            var valueProvider = new FormValueProvider(
                BindingSource.Form,
                form,
                CultureInfo.CurrentCulture);

            context.ValueProviders.Add(valueProvider);
        }
Ejemplo n.º 12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            checkoutForm.Visible    = true;
            checkoutMessage.Visible = false;

            if (IsPostBack)
            {
                FormValueProvider provider;
                Order             myOrder = new Order();
                if (TryUpdateModel(myOrder,
                                   provider = new FormValueProvider(ModelBindingExecutionContext)))
                {
                    myOrder.OrderLines = new List <OrderLine>();

                    Cart myCart = SessionHelper.GetCart(Session);

                    foreach (CartLine line in myCart.Lines)
                    {
                        myOrder.OrderLines.Add(new OrderLine
                        {
                            Order    = myOrder,
                            Game     = line.Game,
                            Quantity = line.Quantity
                        });
                    }

                    new Repository().SaveOrder(myOrder);
                    myCart.Clear();

                    checkoutForm.Visible    = false;
                    checkoutMessage.Visible = true;
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 上傳圖像
        /// </summary>
        /// <param name="httpRequest">httpRequest</param>
        /// <returns>List<string></returns>
        public async Task <List <string> > UploadImages(HttpRequest httpRequest)
        {
            try
            {
                List <string>     filePaths         = new List <string>();
                FormValueProvider formValueProvider = await httpRequest.StreamFile((file) =>
                {
                    this.logger.LogInformation($"Start Upload Image >>> file:{file.FileName}");
                    string fileExtensionName = Path.GetExtension(file.FileName);
                    string fileName          = this.GetNewFileName(fileExtensionName);
                    string fileUrl           = $"images/event/{fileName}".ToLower();
                    string filePath          = $"{AppSettingHelper.Appsetting.CdnPath}/{fileUrl}".ToLower();
                    string fileDirectoryName = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(fileDirectoryName))
                    {
                        Directory.CreateDirectory(fileDirectoryName);
                    }

                    filePaths.Add(fileUrl);
                    return(File.Create(filePath));
                });

                this.logger.LogInformation($"Finish Upload Image >>> file:{JsonConvert.SerializeObject(filePaths)}");
                return(filePaths);
            }
            catch (Exception ex)
            {
                this.logger.LogError($"Upload Images Error\n{ex}");
                return(new List <string>());
            }
        }
Ejemplo n.º 14
0
        public static async Task <FormValueProvider> StreamFilesModel(this HttpRequest request, Func <IFormFile, Task> func)
        {
            if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
            {
                throw new Exception($"Expected a multipart request, but got {request.ContentType}");
            }

            // Used to accumulate all the form url encoded key value pairs in the request.
            var formAccumulator = new KeyValueAccumulator();
            var boundary        = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader          = new MultipartReader(boundary, request.Body);
            var section         = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDispositionHeader);

                if (hasHeader && contentDispositionHeader.IsFileDisposition())
                {
                    FileMultipartSection fileSection = section.AsFileSection();

                    // process file stream
                    await func(new MultipartFile(fileSection.FileStream, fileSection.Name, fileSection.FileName) {
                        ContentType        = fileSection.Section.ContentType,
                        ContentDisposition = fileSection.Section.ContentDisposition
                    });
                }
                else if (hasHeader && contentDispositionHeader.IsFormDisposition())
                {
                    // Content-Disposition: form-data; name="key"
                    // Do not limit the key name length here because the multipart headers length limit is already in effect.
                    var key      = HeaderUtilities.RemoveQuotes(contentDispositionHeader.Name);
                    var encoding = section.GetEncoding();
                    using (var streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) {
                        // The value length limit is enforced by MultipartBodyLengthLimit
                        var value = await streamReader.ReadToEndAsync();

                        if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                        {
                            value = String.Empty;
                        }

                        formAccumulator.Append(key.Value, value);

                        if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                        {
                            throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                        }
                    }
                }

                // Drains any remaining section body that has not been consumed and reads the headers for the next section.
                section = request.Body.CanSeek && request.Body.Position == request.Body.Length ? null : await reader.ReadNextSectionAsync();
            }
            // Bind form data to a model
            var formValueProvider = new FormValueProvider(BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture);

            return(formValueProvider);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Parses the HttpRequest into it's form data and files
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task <FileStreamHelperModel> ParseAsync(HttpRequest request, bool fileOnly = false)
        {
            (var formSection, var fileSections) = await ExtractSections(request, fileOnly);

            FormValueProvider formValues = await ParseFormBody(formSection);

            return(new FileStreamHelperModel(formValues, fileSections));
        }
        static async Task <T> UpdateModel <T>(FormValueProvider form, ControllerBase controller) where T : class, new()
        {
            var model = new T();
            await controller.TryUpdateModelAsync <T>(model, prefix : "", valueProvider : form);

            controller.TryValidateModel(model);
            return(model);
        }
Ejemplo n.º 17
0
        private async Task <T> GetBindModel <T>() where T : class, new()
        {
            var model             = new T();
            var formValueProvider = new FormValueProvider(BindingSource.Form, Request.Form, CultureInfo.CurrentCulture);

            await TryUpdateModelAsync(model, prefix : "", valueProvider : formValueProvider);

            return(model);
        }
Ejemplo n.º 18
0
        private static async Task UpdateAndValidateForm <T>(Controller controller, T model, Dictionary <string, StringValues> forms) where T : class
        {
            var formValueProvider = new FormValueProvider(BindingSource.Form,
                                                          new FormCollection(forms), CultureInfo.CurrentCulture);

            var bindingSuccessful = await controller.TryUpdateModelAsync(model, prefix : "",
                                                                         valueProvider : formValueProvider);

            controller.TryValidateModel(model);
        }
Ejemplo n.º 19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                Customer customer = new Customer();

                IValueProvider provider =
                    new FormValueProvider(ModelBindingExecutionContext);
                Context context = new Context();
                context.Customers.Add(customer);
                context.SaveChanges();
            }
        }
Ejemplo n.º 20
0
    protected override IEnumerableValueProvider GetEnumerableValueProvider(
        BindingSource bindingSource,
        Dictionary <string, StringValues> values,
        CultureInfo culture)
    {
        var emptyValueProvider = new QueryStringValueProvider(bindingSource, new QueryCollection(), culture);
        var valueProvider      = new FormValueProvider(bindingSource, new FormCollection(values), culture);

        return(new CompositeValueProvider()
        {
            emptyValueProvider, valueProvider
        });
    }
Ejemplo n.º 21
0
        private IEnumerable <FapDynamicObject> GetRows(FormValueProvider formValueProvider, IEnumerable <FapColumn> columns)
        {
            IDictionary <string, string> rowsDic = formValueProvider.GetKeysFromPrefix("rows");

            foreach (var row in rowsDic)
            {
                FapDynamicObject keyValues = new FapDynamicObject(columns);
                foreach (var cell in formValueProvider.GetKeysFromPrefix(row.Value))
                {
                    keyValues.SetValue(cell.Key, formValueProvider.GetValue(cell.Value));
                }
                yield return(keyValues);
            }
        }
Ejemplo n.º 22
0
        static T UpdateJsonModel <T>(FormValueProvider form, string modelName) where T : class, new()
        {
            var modelValue = form.GetValue(modelName);

            if (modelValue == null)
            {
                throw new ArgumentNullException(nameof(modelName), $"Could not find form value with key: {modelName}");
            }

            var json  = modelValue.ToString();
            var model = JsonSerializer.Deserialize <T>(json, new JsonSerializerOptions {
                PropertyNameCaseInsensitive = true
            });

            return(model);
        }
        public async Task ShouldNotBindIncompleteValueCollectionForDateTime_MissingYear()
        {
            var formCollection = new FormCollection(new Dictionary <string, StringValues>()
            {
                { "Month", "12" },
            });

            var binder = new DateMonthYearModelBinder();

            var vp = new FormValueProvider(BindingSource.Form, formCollection, CultureInfo.CurrentCulture);

            var context = GetBindingContext(vp, typeof(string));

            await binder.BindModelAsync(context);

            context.Result.Model.Should().BeNull();
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> Index()
        {
            if (ModelState.IsValid)
            {
                FormValueProvider valueProvider = null;
                var   viewModel    = new ImageUploadModel();
                bool  updateResult = false;
                Image binary;

                binary = await _binaryRepository.InsertAsync(
                    async (stream) =>
                {
                    valueProvider = await Request.StreamFile(stream);
                },
                    async() =>
                {
                    updateResult = await TryUpdateModelAsync(
                        viewModel, prefix: "", valueProvider: valueProvider);
                    if (updateResult)
                    {
                        // TODO: read image information from request
                        // TODO: get image dimensions, etc
                        binary          = new Image();
                        binary.UserId   = 4;
                        binary.Checksum = viewModel.Checksum;
                        binary.Width    = 100;
                        binary.Height   = 200;
                        return(binary);
                    }
                    else
                    {
                        return(null);
                    }
                }
                    );

                //await _binaryRepository.ExportToFileAsync(img, "/home/sergey/Projects/crystalocean/image.tmp");

                if (updateResult)
                {
                    return(Ok(viewModel));
                }
            }

            return(BadRequest(ModelState));
        }
        private static async Task <TDto> GetModel <TDto>(ControllerBase controller, KeyValueAccumulator formAccumulator)
            where TDto : class, new()
        {
            var valueProvider = new FormValueProvider(
                BindingSource.Form,
                new FormCollection(formAccumulator.GetResults()),
                CultureInfo.CurrentCulture);

            var model = Activator.CreateInstance <TDto>();

            if (await controller.TryUpdateModelAsync(model, string.Empty, valueProvider) == false)
            {
                throw new InvalidOperationException($"Could not update model {model.GetType().Name}.");
            }

            return(model);
        }
Ejemplo n.º 26
0
        public static ModelBindingContext MockModelBindingContext(string draw, string length, string start, string searchValue, string searchRegex, IDictionary <string, object> additionalParameters, Core.NameConvention.IRequestNameConvention requestNameConvention)
        {
            // Request properties.
            var formCollection = new Dictionary <string, StringValues>()
            {
                { requestNameConvention.Length, length },
                { requestNameConvention.Start, start },
                { requestNameConvention.SearchValue, searchValue },
                { requestNameConvention.IsSearchRegex, searchRegex }
            };

            if (!String.IsNullOrWhiteSpace(draw))
            {
                formCollection.Add(requestNameConvention.Draw, draw);
            }

            // Aditional parameters.
            if (additionalParameters != null)
            {
                foreach (var keypair in additionalParameters)
                {
                    formCollection.Add(keypair.Key, Convert.ToString(keypair.Value));
                }
            }

            // Value provider for request properties.
            var valueProvider = new FormValueProvider(new BindingSource("a", "a", false, true), new FormCollection(formCollection), new System.Globalization.CultureInfo("en-US"));


            // Model metadata.
            var x             = new Microsoft.AspNetCore.Mvc.Internal.DefaultCompositeMetadataDetailsProvider(null);
            var modelMetadata = new Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadataProvider(x).GetMetadataForType(typeof(Core.IDataTablesRequest));

            //var modelMetadata = new Microsoft.AspNet.Mvc.ModelBinding.Metadata. ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Core.IDataTablesRequest));

            return(new DefaultModelBindingContext()
            {
                ModelName = "moq",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            });
        }
Ejemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Create a value provider to get values from
            var formValues = new FormValueProvider(this.GetModelBindingExecutionContext());

            // Create an instance of your model class
            var model = new PageModel();

            // Bind onto the model instance from the form collection
            TryUpdateModel(model, formValues);

            if (ModelState.IsValid)
            {
                // Do stuff
            }
            else
            {
                // Show errors
            }
        }
Ejemplo n.º 28
0
        public async Task TestModelBinderDateTime()

        {
            var binder = new DateTimeModelBinder();

            var formCollection = new FormCollection(
                new Dictionary <string, StringValues>()
            {
                { "startDate", new StringValues("14.01.2008") },
            });
            var vp = new FormValueProvider(BindingSource.Form, formCollection, CultureInfo.CurrentCulture);

            var context = GetBindingContext(vp, typeof(DateTime?));

            await binder.BindModelAsync(context);

            var resultModel = context.Result.Model as DateTime?;

            Assert.NotNull(resultModel);
            Assert.True(((DateTime)resultModel).Day == 14);
            //TODO asserts
        }
Ejemplo n.º 29
0
        public static ModelBindingContext MockModelBindingContextWithInvalidRequest()
        {
            // Request properties.
            var formCollection = new Dictionary <string, StringValues>();

            // Value provider for request properties.
            var valueProvider = new FormValueProvider(new BindingSource("a", "a", false, true), new FormCollection(formCollection), new System.Globalization.CultureInfo("en-US"));

            // Model metadata.

            var x             = new Microsoft.AspNetCore.Mvc.Internal.DefaultCompositeMetadataDetailsProvider(null);
            var modelMetadata = new Microsoft.AspNetCore.Mvc.ModelBinding.Metadata.DefaultModelMetadataProvider(x).GetMetadataForType(typeof(Core.IDataTablesRequest));

            //var modelMetadata = new Microsoft.AspNet.Mvc.ModelBinding.Metadata. ModelMetadataProviders.Current.GetMetadataForType(null, typeof(Core.IDataTablesRequest));

            return(new DefaultModelBindingContext()
            {
                ModelName = "moq",
                ValueProvider = valueProvider,
                ModelMetadata = modelMetadata
            });
        }
Ejemplo n.º 30
0
        //=== Helpers

        /// <summary> Looks for value provider result. </summary>
        private object FindValue(ModelBindingContext bindingContext)
        {
            ValueProviderCollection vpc = bindingContext.ValueProvider as ValueProviderCollection;

            foreach (object vp in vpc)
            {
                if (vp is FormValueProvider)
                {
                    FormValueProvider fvp = (FormValueProvider)vp;

                    ValueProviderResult vpr = fvp.GetValue(bindingContext.ModelName);

                    if (vpr != null)
                    {
                        return(vpr);
                    }
                }
                else if (vp is DictionaryValueProvider <object> )
                {
                    DictionaryValueProvider <object> dvp = (DictionaryValueProvider <object>)vp;

                    ValueProviderResult vpr = dvp.GetValue(bindingContext.ModelName);

                    if (vpr != null)
                    {
                        return(vpr);
                    }
                    else if (dvp.ContainsPrefix(bindingContext.ModelName))
                    {
                        return(vp);
                    }
                }
            }

            return(null);
        }