Получение привязки модели по умолчанию, работающей с привязкой пользовательской модели в WebPI и asp.net mVC 4

Я создал custom Model binder работает нормально со всеми свойствами.
Но проблема в том, что мне не хватает связывания моделей по умолчанию.
я использую DataAnotations для моих объектов, и я хочу применить свой пользовательский связыватель модели только для Enums.
Как я могу получить пользовательское связывание модели вместе со связыванием модели по умолчанию.
В пользовательском связывателе моделей у меня есть следующий код.


 public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var json = actionContext.Request.Content.ReadAsStringAsync().Result;
            if (!string.IsNullOrEmpty(json))
            {
                var jsonObject = (JObject) Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                var jsonPropertyNames = jsonObject.Properties().Select(p => p.Name).ToList();

                var requiredProperties = bindingContext.ModelType.GetProperties().Where(p =>p.GetCustomAttributes(typeof(RequiredAttribute),
                                                                                           false).Any()).ToList();

                var missingProperties = requiredProperties.Where(bindingProperty => !jsonPropertyNames.Contains(bindingProperty.Name)).ToList();

                if (missingProperties.Count > 0)
                {

                    missingProperties.ForEach(
                        prop =>
                            {
                                if (prop.PropertyType.IsEnum)
                                    actionContext.ModelState.AddModelError(prop.Name, prop.Name + " is Required");

                            });
                }

                var nullProperties = requiredProperties.Except(missingProperties).ToList();

                if (nullProperties.Count > 0)
                {
                    nullProperties.ForEach(p =>
                        {
                            var jsonvalue = JObject.Parse(json);
                            var value = (JValue)jsonvalue[p.Name];
                            if (value.Value == null)
                            {
                                actionContext.ModelState.AddModelError(p.Name, p.Name + " is Required");
                            }

                        });
                }

            }
            // Now we can try to eval the object's properties using reflection.
            return true;
        }

0 ответов

Другие вопросы по тегам