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


C# Mvc.ModelBindingContext类代码示例

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


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

示例1: BindModel

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(AddSheduleViewModel))
            {
                HttpRequestBase request = controllerContext.HttpContext.Request;
                var model = base.BindModel(controllerContext, bindingContext) as AddSheduleViewModel;
                bindingContext.ModelState.Clear();
                var shedule = request.Form["Shedule"];
                    Regex reg = new Regex(@"\d{1,2}:\d{1,2}");
                    MatchCollection matches = reg.Matches(shedule);
                if (matches.Count != 0)
                {
                    try
                {

                        model.Shedule = matches.Cast<Match>().Select(x => TimeSpan.Parse(x.Value)).ToList();

                }
                catch(Exception ex)
                {
                        NLog.LogManager.GetCurrentClassLogger().Error(ex);
                        bindingContext.ModelState.AddModelError("", "Неверно заполнено расписание");
                }
                }
                return model;

            }
            else
            {
                return base.BindModel(controllerContext, bindingContext);
            }
        }
开发者ID:dmitriymatus,项目名称:bus_shedule_mvc5,代码行数:32,代码来源:SheduleBinder.cs

示例2: BindModel

        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            //get the car from the session

            Cart cart = null;
            if (controllerContext.HttpContext.Session != null)
            {
                cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
            }

            //create the Cart if there wasn't one in the session data

            if(cart == null)
            {
                cart = new Cart();

                if (controllerContext.HttpContext.Session != null)
                {
                    controllerContext.HttpContext.Session[sessionKey] = cart;
                }
            }

            return cart;
        }
开发者ID:agbald02,项目名称:SoundBarrierHunting,代码行数:25,代码来源:CartModelBinder.cs

示例3: ValidateModel

		void ValidateModel(object model, ModelBindingContext bindingContext, List<int> validatedObjects = null)
		{
			validatedObjects = validatedObjects ?? new List<int>();
			
			var typeDescriptor = GetTypeDescriptor(model, model.GetType());
			
			// validate the model
			foreach (ValidationAttribute attribute in typeDescriptor.GetAttributes().OfType<ValidationAttribute>()) {
				if (!attribute.IsValid (bindingContext.Model)) {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, attribute.FormatErrorMessage(bindingContext.ModelName));
                }
				validatedObjects.Add (model.GetHashCode());
            }
			
			// validate properties, recurse if necessary
			foreach (PropertyDescriptor property in typeDescriptor.GetProperties()) {
				var propInstance = property.GetValue (model);
				
                foreach (ValidationAttribute attribute in property.Attributes.OfType<ValidationAttribute>()) {
                    if (!attribute.IsValid(propInstance)) {
                        bindingContext.ModelState.AddModelError(property.Name, attribute.FormatErrorMessage(property.Name));
                        if (propInstance != null) {
                            validatedObjects.Add(propInstance.GetHashCode());
                        }
                    }
                    else if (propInstance != null) {
                        ValidateModel(propInstance, bindingContext, validatedObjects);
                    }
                }
			}
		}
开发者ID:bunglestink,项目名称:YFSC.NET,代码行数:31,代码来源:JsonModelBinder.cs

示例4: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            CheckPropertyFilter(bindingContext);
            ExtensibleModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);

            IExtensibleModelBinder binder = Providers.GetBinder(controllerContext, newBindingContext);
            if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName)
                && bindingContext.FallbackToEmptyPrefix && bindingContext.ModelMetadata.IsComplexType)
            {
                // fallback to empty prefix?
                newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */);
                binder = Providers.GetBinder(controllerContext, newBindingContext);
            }

            if (binder != null)
            {
                bool boundSuccessfully = binder.BindModel(controllerContext, newBindingContext);
                if (boundSuccessfully)
                {
                    // run validation and return the model
                    newBindingContext.ValidationNode.Validate(controllerContext, null /* parentNode */);
                    return newBindingContext.Model;
                }
            }

            return null; // something went wrong
        }
开发者ID:JokerMisfits,项目名称:linux-packaging-mono,代码行数:27,代码来源:ExtensibleModelBinderAdapter.cs

示例5: BindModel

        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>
        /// The bound value.
        /// </returns>
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            FacebookClient client = _config.ClientProvider.CreateClient();
            dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
                controllerContext.HttpContext,
                rawSignedRequest =>
                {
                    return client.ParseSignedRequest(rawSignedRequest);
                });
            if (signedRequest != null)
            {
                string accessToken = signedRequest.oauth_token;
                string userId = signedRequest.user_id;
                client.AccessToken = accessToken;
                return new FacebookContext
                {
                    Client = client,
                    SignedRequest = signedRequest,
                    AccessToken = accessToken,
                    UserId = userId,
                    Configuration = _config
                };
            }
            else
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest);
            }

            return null;
        }
开发者ID:tlycken,项目名称:aspnetwebstack,代码行数:38,代码来源:FacebookContextModelBinder.cs

示例6: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository());
            User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details;

            int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId"));
            int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId"));
            string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL");
            string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim();

            IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId);

            string[] splitIds = selectedProfilePictureIds.Split(',');
            List<int> selectedProfilePictures = new List<int>();

            foreach (string id in splitIds) {
                if (id != string.Empty) {
                    selectedProfilePictures.Add(Int32.Parse(id));
                }
            }

            return new PhotosModel() {
                UserId = myUserId,
                ProfilePictureURL = myProfilePictureURL,
                Photos = myPhotos,
                SelectedPhotos = selectedProfilePictures
            };
        }
开发者ID:henryksarat,项目名称:Have-A-Voice,代码行数:28,代码来源:UserPicturesModelBinder.cs

示例7: BindModel

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ProjectNewViewModel model = (ProjectNewViewModel)bindingContext.Model ??
                (ProjectNewViewModel)DependencyResolver.Current.GetService(typeof(ProjectNewViewModel));
            bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
            string searchPrefix = (hasPrefix) ? bindingContext.ModelName + ".":"";

            //since viewmodel contains custom types like project make sure project is not null and to pass key arround for value providers
            //use Project.Name even if your makrup dont have Project prefix
            model.Project = new Project();
            //populate the fields of the model
            model.Project.ProjectId = 0;
            model.Project.Name = GetValue(bindingContext, searchPrefix, "Project.Name");
            model.Project.Url = GetValue(bindingContext, searchPrefix, "Project.Url");
            model.Project.CreatedOn  =  DateTime.Now;
            model.Project.UpdatedOn = DateTime.Now;
            model.Project.isDisabled = GetCheckedValue(bindingContext, searchPrefix, "Project.isDisabled");
            model.Project.isFeatured = GetCheckedValue(bindingContext, searchPrefix, "Project.isFeatured");
            model.Project.GroupId = int.Parse(GetValue(bindingContext, searchPrefix, "Project.GroupId"));
            model.Project.Tags = new List<Tag>();

            foreach (var tagid in GetValue(bindingContext, searchPrefix, "Tags").Split(','))
            {
                var tag = new Tag { TagId = int.Parse(tagid)};
                model.Project.Tags.Add(tag);
            }

            var total = model.Project.Tags.Count;

            return model;
        }
开发者ID:najamsk,项目名称:BigApp,代码行数:31,代码来源:NewProjectModelBinder.cs

示例8: BindModel

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (!string.IsNullOrEmpty(displayFormat) && value != null)
            {
                DateTime date;
                displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
                // use the format specified in the DisplayFormat attribute to parse the date
                if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                {
                    return date;
                }
                else
                {
                    bindingContext.ModelState.AddModelError(
                        bindingContext.ModelName,
                        string.Format("{0} is an invalid date format", value.AttemptedValue)
                    );
                }
            }

            return base.BindModel(controllerContext, bindingContext);
        }
开发者ID:nzhul,项目名称:mvcstart,代码行数:25,代码来源:BulgarianTimeModelBinder.cs

示例9: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);

            return date;
        }
开发者ID:hbiarge,项目名称:Testing-HackLab,代码行数:7,代码来源:LocaleDateTimeBinder.cs

示例10: SetProperty

 protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
 {
     base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
     switch (propertyDescriptor.Name)
     {
         case "ClientName" :
             if (string.IsNullOrEmpty((string)value))
             {
                 bindingContext.ModelState.AddModelError("ClientName", "");
             }
             break;
         case "Date":
             if((bindingContext.ModelState.IsValidField("Date")) && (DateTime.Now>(DateTime)value))
             {
                 bindingContext.ModelState.AddModelError("Date", "");
             }
             break;
         case "TermsAccepted":
             if (!(bool)value)
             {
                 bindingContext.ModelState.AddModelError("TermsAccepted", "");
             }
             break;
     }
 }
开发者ID:ShvecovEvgeniy,项目名称:MVCProject,代码行数:25,代码来源:ValidationModelBunder.cs

示例11: BindModel

        public object BindModel(ControllerContext controllerContext,
                                ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            ModelState modelState = new ModelState {Value = valueResult};

            object actualValue = null;
            try
            {
                if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
                {
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                                                CultureInfo.CurrentCulture);
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
开发者ID:pragmasolutions,项目名称:avicola,代码行数:25,代码来源:DecimalModelBinder.cs

示例12: CreateModel

        protected override object CreateModel(ModelBindingContext bindingContext, Type modelType)
        {
            if (IsBasicType(modelType))
            {
                return base.GetValue(controllerContext, modelName, modelType, modelState);
            }

            if (IsSimpleType(modelType))
            {
                ModelBinderResult
            }

            var instance = Activator.CreateInstance(modelType);

            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(instance))
            {
                if (IsBasicType(descriptor.PropertyType))
                {
                    var obj = GetBinder(descriptor.PropertyType).GetValue(controllerContext, descriptor.Name, descriptor.PropertyType, modelState);
                    descriptor.SetValue(instance, obj);
                }
                else
                {
                    descriptor.SetValue(instance, Activator.CreateInstance(descriptor.PropertyType));
                    BindComplexType(controllerContext, descriptor.PropertyType, descriptor.GetValue(instance), modelState);
                }
            }
            return instance;
        }
开发者ID:bclubb,项目名称:yabe,代码行数:29,代码来源:CustomModelBinder.cs

示例13: PerformBindModel

        public static object PerformBindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var idName = string.IsNullOrEmpty(bindingContext.ModelName) ? "id" : bindingContext.ModelName;


            var valueProviderResult = bindingContext.GetValue(idName);
            if (valueProviderResult == null)
            {
                return null;
            }

            var rawId = valueProviderResult.ConvertTo(typeof(string)) as string;

            var parseResult = HiveId.TryParse(rawId);
            if (parseResult.Success)
            {
                //add the bound value to model state if it's not already there, generally only simple props will be there
                if (!bindingContext.ModelState.ContainsKey(idName))
                {
                    bindingContext.ModelState.Add(idName, new ModelState());
                    bindingContext.ModelState.SetModelValue(idName, new ValueProviderResult(parseResult.Result, parseResult.Result.ToString(), null));
                }
            }

            return parseResult.Result;
        }
开发者ID:RebelCMS,项目名称:rebelcmsxu5,代码行数:26,代码来源:HiveIdModelBinder.cs

示例14: BindModel

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext", "controllerContext is null.");
            if (bindingContext == null)
                throw new ArgumentNullException("bindingContext", "bindingContext is null.");

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

            if (value == null) return null;

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

            try
            {
                var date = value.ConvertTo(typeof(DateTime), CurrentRequestData.CultureInfo);

                return date;
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
                return null;
            }
        }
开发者ID:neozhu,项目名称:Ecommerce,代码行数:25,代码来源:CultureAwareDateBinder.cs

示例15: CreateModel

        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            string dataRuleTypeStr;

            string dataruleTypeName = !string.IsNullOrWhiteSpace(bindingContext.ModelName) ? (bindingContext.ModelName + ".DataRuleType") : "DataRuleType";

            dataRuleTypeStr = controllerContext.HttpContext.Request[dataruleTypeName];

            if (string.IsNullOrEmpty(dataRuleTypeStr))
            {
                return null;
            }
            var dataRuleInt = Int32.Parse(dataRuleTypeStr);
            DataRuleType dataRuleTypeEnum = (DataRuleType)dataRuleInt;
            object model = null;
            switch (dataRuleTypeEnum)
            {
                case DataRuleType.Folder:
                    model = new FolderDataRule();
                    break;
                case DataRuleType.Schema:
                    model = new SchemaDataRule();
                    break;
                case DataRuleType.Category:
                    model = new CategoryDataRule();
                    break;
            }
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
            return model;
        }
开发者ID:jason1234,项目名称:CMS,代码行数:30,代码来源:DataRuleBinder.cs


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