• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ModelBinding.ModelBindingContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: DefaultOptions

        public void DefaultOptions()
        {
            var binder = new GeocodeOptionsModelBinding();
            var httpControllerContext = new HttpControllerContext
                {
                    Request =
                        new HttpRequestMessage(HttpMethod.Get,
                                               "http://webapi/api/v1/geocode/address/zone")
                };
            var httpActionContext = new HttpActionContext {ControllerContext = httpControllerContext};
            var moc = new Mock<ModelMetadataProvider>();
            var modelBindingContext = new ModelBindingContext
                {
                    ModelMetadata =
                        new ModelMetadata(moc.Object, null, null, typeof (GeocodeOptions), null)
                };

            var successful = binder.BindModel(httpActionContext, modelBindingContext);

            Assert.That(successful, Is.True);

            var model = modelBindingContext.Model as GeocodeOptions;

            Assert.That(model, Is.Not.Null);

            Assert.That(model.AcceptScore, Is.EqualTo(70));
            Assert.That(model.WkId, Is.EqualTo(26912));
            Assert.That(model.SuggestCount, Is.EqualTo(0));
            Assert.That(model.PoBox, Is.False);
            Assert.That(model.Locators, Is.EqualTo(LocatorType.All));
        }
开发者ID:agrc,项目名称:api.mapserv.utah.gov,代码行数:31,代码来源:GeocodeOptionTests.cs


示例17: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var model = (DashboardRequest) bindingContext.Model ?? new DashboardRequest();

            var hasPrefix = bindingContext
                .ValueProvider
                .ContainsPrefix(bindingContext.ModelName);

            var searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : string.Empty;

            Dimension dimension;
            Section section;

            Enum.TryParse(actionContext.ActionDescriptor.ActionName, out dimension);
            Enum.TryParse(GetValue(bindingContext, searchPrefix, "Section"), out section);

            model.ActivityGroupId =
                TryParser.Nullable<Guid>(GetValue(bindingContext, searchPrefix, "ActivityGroupId"));
            model.CostCode = GetValue(bindingContext, searchPrefix, "CostCode");
            model.StartDate = GetDateTime(bindingContext, searchPrefix, "StartDate");
            model.EndDate = GetDateTime(bindingContext, searchPrefix, "EndDate");
            model.Dimension = dimension;
            model.Section = section;

            bindingContext.Model = model;

            return true;
        }
开发者ID:Warrenn,项目名称:Carbon.MVC,代码行数:28,代码来源:DashboardRequestModelBinderAttribute.cs


示例18: AllOptions

        public void AllOptions()
        {
            var binder = new GeocodeOptionsModelBinding();
            var httpControllerContext = new HttpControllerContext
                {
                    Request =
                        new HttpRequestMessage(HttpMethod.Get,
                                               "http://webapi/api/v1/geocode/address/zone?spatialReference=111&format=geojson&callback=p&acceptScore=80&suggest=1&locators=roadCenterlines&pobox=tRue&apiKey=AGRC-ApiExplorer")
                };
            var httpActionContext = new HttpActionContext {ControllerContext = httpControllerContext};
            var moc = new Mock<ModelMetadataProvider>();
            var modelBindingContext = new ModelBindingContext
                {
                    ModelMetadata =
                        new ModelMetadata(moc.Object, null, null, typeof (GeocodeOptions), null)
                };

            var successful = binder.BindModel(httpActionContext, modelBindingContext);

            Assert.That(successful, Is.True);

            var model = modelBindingContext.Model as GeocodeOptions;
            
            Assert.That(model, Is.Not.Null);

            Assert.That(model.AcceptScore, Is.EqualTo(80));
            Assert.That(model.WkId, Is.EqualTo(111));
            Assert.That(model.SuggestCount, Is.EqualTo(1));
            Assert.That(model.PoBox, Is.True);
            Assert.That(model.Locators, Is.EqualTo(LocatorType.RoadCenterlines));
        }
开发者ID:agrc,项目名称:api.mapserv.utah.gov,代码行数:31,代码来源:GeocodeOptionTests.cs


示例19: BindModel

        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <returns>
        /// true if model binding is successful; otherwise, false.
        /// </returns>
        /// <param name="actionContext">The action context.</param><param name="bindingContext">The binding context.</param>
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var queryStructure = new QueryStructure();

            var query = actionContext.Request.GetQueryNameValuePairs().ToArray();

            int pageSize;
            if (query.Any(x => x.Key.InvariantEquals("pageSize")) && int.TryParse(query.Single(x => x.Key.InvariantEquals("pageSize")).Value, out pageSize))
            {
                queryStructure.PageSize = pageSize;
            }

            int pageIndex;
            if (query.Any(x => x.Key.InvariantEquals("pageIndex")) && int.TryParse(query.Single(x => x.Key.InvariantEquals("pageIndex")).Value, out pageIndex))
            {
                queryStructure.PageIndex = pageIndex;
            }

            if (query.Any(x => x.Key.InvariantEquals("lucene")))
            {
                queryStructure.Lucene = query.Single(x => x.Key.InvariantEquals("lucene")).Value;
            }

            bindingContext.Model = queryStructure;
            return true;
        }
开发者ID:robertjf,项目名称:UmbracoRestApi,代码行数:33,代码来源:QueryStructureModelBinder.cs


示例20: BindModel

        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var keyValueModel = actionContext.Request.RequestUri.ParseQueryString();

            var spatialReference = keyValueModel["spatialReference"];
            var distance = keyValueModel["distance"];

            int wkid;
            double distanceValue;

            int.TryParse(string.IsNullOrEmpty(spatialReference) ? "26912" : spatialReference, out wkid);
            double.TryParse(string.IsNullOrEmpty(distance) ? "5" : distance, out distanceValue);

            if (distanceValue < 5)
            {
                distanceValue = 5;
            }

            bindingContext.Model = new ReverseGeocodeOptions
            {
                Distance = distanceValue,
                WkId = wkid
            };

            return true;
        }
开发者ID:agrc,项目名称:api.mapserv.utah.gov,代码行数:26,代码来源:ReverseGeocodeOptionsModelBinding.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# OData.Delta类代码示例发布时间:2022-05-26
下一篇:
C# Metadata.ModelMetadataProvider类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap