Acheive Default model Binding working with custom model binder in WebPI and asp.net mVC 4

↘锁芯ラ 提交于 2020-01-06 14:54:33

问题


I created a custom Model binder working fine with all the properties.
But the issue is I am missing the default modelbinding.
I am using DataAnotations for my objects and I want to apply my custom model binder for Enums only.
How can I achieve the custom Model binder along with default model binding.
In the custom Model Binder, I have the code as following.


 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;
        }

来源:https://stackoverflow.com/questions/20048846/acheive-default-model-binding-working-with-custom-model-binder-in-webpi-and-asp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!