当前位置: 首页>>代码示例>>C#>>正文


C# ModelBinding.ModelBindingContext类代码示例

本文整理汇总了C#中System.Web.Http.ModelBinding.ModelBindingContext的典型用法代码示例。如果您正苦于以下问题:C# ModelBindingContext类的具体用法?C# ModelBindingContext怎么用?C# ModelBindingContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ModelBindingContext类属于System.Web.Http.ModelBinding命名空间,在下文中一共展示了ModelBindingContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: BindModel

        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(Hash))
                return false;
            
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (value == null)
                return false;

            string valueStr = value.RawValue as string;
            if (valueStr == null)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type.");
                return false;
            }

            Hash result;
            try
            {
                result = Hash.Parse(valueStr);
            }
            catch
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot parse hash.");
                return false;
            }
            bindingContext.Model = result;
            return true;
        }
开发者ID:jechtom,项目名称:DevUpdater,代码行数:29,代码来源:HashModelBinder.cs

示例2: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var key = bindingContext.ModelName;
            var val = bindingContext.ValueProvider.GetValue(key);
            if (val != null)
            {
                var s = val.AttemptedValue;
                if (s != null)
                {
                    var elementType = bindingContext.ModelType.GetElementType();
                    var converter = TypeDescriptor.GetConverter(elementType);
                    var values = Array.ConvertAll(s.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries),
                        x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });

                    var typedValues = Array.CreateInstance(elementType, values.Length);

                    values.CopyTo(typedValues, 0);

                    bindingContext.Model = typedValues;
                }
                else
                {
                    // change this line to null if you prefer nulls to empty arrays
                    bindingContext.Model = Array.CreateInstance(bindingContext.ModelType.GetElementType(), 0);
                }
                return true;
            }
            return false;
        }
开发者ID:MGTSr,项目名称:StockExchange,代码行数:29,代码来源:CommaSeparatedArrayModelBinder.cs

示例3: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            string content = actionContext.Request.Content.ReadAsStringAsync().Result;

            try
            {
                // Try to parse as Json
                bindingContext.Model = Parse(content);
            }
            catch (Exception)
            {
                // Parse the QueryString
                _queryString = GetQueryString(content);
                bindingContext.Model = Parse(_queryString);
            }

            return true;
        }
开发者ID:hanssens,项目名称:OpenKendoBinder,代码行数:27,代码来源:CustomApiModelBinder.cs

示例4: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            //NOTE: Validation is done in the filter
            if (!actionContext.Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = HttpContext.Current.Server.MapPath("~/App_Data/TEMP/FileUploads");
            //ensure it exists
            Directory.CreateDirectory(root);
            var provider = new MultipartFormDataStreamProvider(root);

            var task = Task.Run(() => GetModel(actionContext.Request.Content, provider))
                .ContinueWith(x =>
                {
                    if (x.IsFaulted && x.Exception != null)
                    {
                        throw x.Exception;
                    }
                    bindingContext.Model = x.Result;
                });
            
            task.Wait();
            
            return bindingContext.Model != null;
        }
开发者ID:jakobloekke,项目名称:Belle,代码行数:27,代码来源:ContentItemBinder.cs

示例5: BindModel

        public override bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
            BindModelOnSuccessOrFail(bindingContext,
                () => ModelBinderUtils.CreateSingleValueArgument(DeserializeContent(actionContext)),
                ModelBinderUtils.CreateSingleValueArgumentForMalformedArgs);

            return true;
        }
开发者ID:NakedObjectsGroup,项目名称:NakedObjectsFramework,代码行数:7,代码来源:SingleValueArgumentBinder.cs

示例6: GetDateTime

 private static DateTime GetDateTime(ModelBindingContext context, string prefix, string key)
 {
     var dateValue = GetValue(context, prefix, key);
     dateValue = dateValue.Replace("\"", string.Empty);
     dateValue = dateValue.Split('T')[0];
     return TryParser.DateTime(dateValue) ?? DateTime.Today;
 }
开发者ID:Warrenn,项目名称:Carbon.MVC,代码行数:7,代码来源:DashboardRequestModelBinderAttribute.cs

示例7: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var jsonStr = actionContext.Request.Content.ReadAsStringAsync().Result;
            var msgObj = Json.Decode(jsonStr);

            bindingContext.Model = new Msg
            {
                UserName = msgObj.UserName,
                Email = msgObj.Email,
                HomePage = msgObj.HomePage,
                Text = msgObj.Text,
                Date = DateTime.Now
            };

            var captchaValidtor = new Recaptcha.RecaptchaValidator
            {
                PrivateKey = ConfigurationManager.AppSettings["ReCaptchaPrivateKey"],
                RemoteIP = ((System.Web.HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress,
                Challenge = msgObj.recaptcha_challenge_field,
                Response = msgObj.recaptcha_response_field
            };

            var recaptchaResponse = captchaValidtor.Validate();
            if (!recaptchaResponse.IsValid)
            {
                actionContext.ModelState.AddModelError("recaptcha_response_field", "Символы не соответствуют картинке.");
            }
            return true;
        }
开发者ID:Zzzaru,项目名称:guestbook,代码行数:29,代码来源:MsgBinder.cs

示例8: BindModel

		public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
		{
			if (bindingContext.ModelType != typeof(coreModel.SearchCriteria))
			{
				return false;
			}

			var qs = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query as string);

			var result = new coreModel.SearchCriteria();

			result.Keyword = qs["q"].EmptyToNull();
			var respGroup = qs["respGroup"].EmptyToNull();
			if (respGroup != null)
			{
				result.ResponseGroup = EnumUtility.SafeParse<coreModel.ResponseGroup>(respGroup, coreModel.ResponseGroup.Default);
			}
			result.StoreIds = qs.GetValues("stores");
			result.CustomerId = qs["customer"].EmptyToNull();
            result.EmployeeId = qs["employee"].EmptyToNull();
			result.Count = qs["count"].TryParse(20);
			result.Start = qs["start"].TryParse(0);
			bindingContext.Model = result;
			return true;
		}
开发者ID:adwardliu,项目名称:vc-community,代码行数:25,代码来源:SearchCriteriaBinder.cs

示例9: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            DemoVector vector;

            if (bindingContext.ModelType != typeof (DemoVector))
            {
                return false;
            }

            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null)
            {
                return false; 
            }

            var text = value.RawValue as string;

            if (DemoVector.TryParse(text, out vector))
            {
                bindingContext.Model = vector;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value to vector.");
            return false;
        }
开发者ID:rajashekarusa,项目名称:WebAPIDesign,代码行数:27,代码来源:DemoVectorModelBinder.cs

示例10: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var nvc = HttpUtility.ParseQueryString(actionContext.Request.RequestUri.Query);
            var model = new GetPagedListParams
            {
                PageSize = int.Parse(nvc["count"]),
                Page = int.Parse(nvc["page"]),
                SortExpression = "Id"
            };

            var sortingKey = nvc.AllKeys.FirstOrDefault(x => x.StartsWith("sorting["));
            if (sortingKey != null)
            {
                model.SortExpression = sortingKey.RemoveStringEntries("sorting[", "]") + " " + nvc[sortingKey];
            }

            model.Filters = nvc.AllKeys.Where(x => x.StartsWith("filter["))
                .ToDictionary(x => x.RemoveStringEntries("filter[", "]"), y => nvc[y]);

            if (nvc.AllKeys.Contains("filter"))
            {
                model.Filters = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(nvc["filter"]);
            }

            bindingContext.Model = model;
            return true;
        }
开发者ID:slaq777,项目名称:lmsystem,代码行数:27,代码来源:GetPagedListParamsModelBinder.cs

示例11: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            // Try to resolve hero
            ValueProviderResult heroValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.Hero));
            Hero hero = null;

            if (!string.IsNullOrWhiteSpace(heroValue?.AttemptedValue))
            {
                Guid heroId = _cryptographyService.DecryptGuid(heroValue.AttemptedValue);
                hero = _heroRepository.GetHero(heroId);
            }

            // Try to resolve begin
            ValueProviderResult beginValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.Begin));
            DateTime? begin = null;
            DateTime beginTry;

            if (!string.IsNullOrWhiteSpace(beginValue?.AttemptedValue) && DateTime.TryParse(beginValue.AttemptedValue, out beginTry))
            {
                begin = beginTry;
            }

            // Try to resolve end
            ValueProviderResult endValue = bindingContext.ValueProvider.GetValue(nameof(FreeToPlayPeriodPropertiesModel.End));
            DateTime? end = null;
            DateTime endTry;

            if (!string.IsNullOrWhiteSpace(endValue?.AttemptedValue) && DateTime.TryParse(endValue.AttemptedValue, out endTry))
            {
                end = endTry;
            }

            bindingContext.Model = new FreeToPlayPeriodPropertiesModel(hero, begin, end);
            return true;
        }
开发者ID:sthiakos,项目名称:General,代码行数:35,代码来源:FreeToPlayPeriodPropertiesModelBinder.cs

示例12: ExecuteBindingAsync

        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            string name = Descriptor.ParameterName;
            Type type = Descriptor.ParameterType;

            string prefix = Descriptor.Prefix;

            IValueProvider vp = CreateValueProvider(this._valueProviderFactories, actionContext);

            ModelBindingContext ctx = new ModelBindingContext()
            {
                ModelName = prefix ?? name,
                FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified
                ModelMetadata = metadataProvider.GetMetadataForType(null, type),
                ModelState = actionContext.ModelState,
                ValueProvider = vp
            };

            IModelBinder binder = this._modelBinderProvider.GetBinder(actionContext, ctx);

            bool haveResult = binder.BindModel(actionContext, ctx);
            object model = haveResult ? ctx.Model : Descriptor.DefaultValue;
            actionContext.ActionArguments.Add(name, model);

            return TaskHelpers.Completed();
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:26,代码来源:ModelBinderParameterBinding.cs

示例13: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof(ObjectId))
            {
                return false;
            }

            var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (val == null)
            {
                return false;
            }

            var value = val.RawValue as string;
            if (value == null)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Wrong value type");
                return false;
            }

            ObjectId result;
            if (ObjectId.TryParse(value, out result))
            {
                bindingContext.Model = result;
                return true;
            }

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Cannot convert value to location");
            return false;
        }
开发者ID:ErikXu,项目名称:SimpleArticle,代码行数:31,代码来源:ObjectIdModelBinder.cs

示例14: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType != typeof (CriteriaModel))
            {
                return false;
            }

            var value = bindingContext.ValueProvider.GetValue("Categories");

            if (value == null)
            {
                return false;
            }

            var categoryJson = value.RawValue as IEnumerable<string>;

            if (categoryJson == null)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Categories cannot be null.");
                return false;
            }

            var categories = categoryJson.Select(JsonConvert.DeserializeObject<CriteriaCategory>).ToList();

            bindingContext.Model = new CriteriaModel {Categories = categories};
            return true;
        }
开发者ID:Romoku,项目名称:AngularResourceWebApiModelBindingSample,代码行数:27,代码来源:CriteriaModelBinder.cs

示例15: BindComplexCollectionFromIndexes_InfiniteIndexes

        public void BindComplexCollectionFromIndexes_InfiniteIndexes()
        {
            // Arrange
            CultureInfo culture = CultureInfo.GetCultureInfo("fr-FR");
            Mock<IModelBinder> mockIntBinder = new Mock<IModelBinder>();
            ModelBindingContext bindingContext = new ModelBindingContext
            {
                ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)),
                ModelName = "someName",
                ValueProvider = new SimpleHttpValueProvider
                {
                    { "someName[0]", "42" },
                    { "someName[1]", "100" },
                    { "someName[3]", "400" }
                }
            };

            HttpActionContext context = ContextUtil.CreateActionContext();
            context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), new SimpleModelBinderProvider(typeof(int), mockIntBinder.Object));

            mockIntBinder
                .Setup(o => o.BindModel(context, It.IsAny<ModelBindingContext>()))
                .Returns((HttpActionContext ec, ModelBindingContext mbc) =>
                {
                    mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType);
                    return true;
                });

            // Act
            List<int> boundCollection = CollectionModelBinder<int>.BindComplexCollectionFromIndexes(context, bindingContext, null /* indexNames */);

            // Assert
            Assert.Equal(new[] { 42, 100 }, boundCollection.ToArray());
            Assert.Equal(new[] { "someName[0]", "someName[1]" }, bindingContext.ValidationNode.ChildNodes.Select(o => o.ModelStateKey).ToArray());
        }
开发者ID:huangw-t,项目名称:aspnetwebstack,代码行数:35,代码来源:CollectionModelBinderTest.cs


注:本文中的System.Web.Http.ModelBinding.ModelBindingContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。