Asp.net mvc 3 - Custom model binding

后端 未结 1 1178
离开以前
离开以前 2021-02-06 16:08

I have a model like this

    public string Name { get; set; }

    public IEnumerable ProjectMembersId { get; set; }

The property Na

1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 16:30

    Try it with BindProperty method:

        public class CustomModelBinder : DefaultModelBinder
        {
            protected override void BindProperty(ControllerContext controllerContext, 
                                                 ModelBindingContext bindingContext, 
                                                 System.ComponentModel.PropertyDescriptor propertyDescriptor)
            {
                if (propertyDescriptor.Name == "ProjectMembersId")
                {
                    var list = new List(5);    
                    var form = controllerContext.HttpContext.Request.Form;    
                    var names = form.AllKeys.Where(x => x.StartsWith("dhxGridObj"));
    
                    foreach (var name in names)
                    {
                        int i;    
                        if (int.TryParse(form.Get(name), out i))
                        {
                            list.Add(i);
                        }
                    }
    
                    SetProperty(controllerContext, bindingContext, propertyDescriptor, list);
                }
                else
                {
                    base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
                }
            }
        }
    

    0 讨论(0)
提交回复
热议问题