MVC Custom type property is not binding in my model

前端 未结 1 1681
暗喜
暗喜 2021-01-13 13:19

I have the following scenario: A C# base project, with all data domains (custom types) that are used by all others projects in the company. So, It´s a little bit hard to mod

相关标签:
1条回答
  • 2021-01-13 13:49

    I found it. I read about custom model binding and then solved my problem with this approach:

    Creating a new class, to override model binding, and checking if the property is of the custom type and then initializes it.

    public class TesteModelBinder2 : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
              NameValueCollection values = controllerContext.HttpContext.Request.Form;
    
              if (propertyDescriptor.PropertyType.Equals(typeof(ShortStrOra)))
              {
                  ShortStrOra value = new ShortStrOra(values[propertyDescriptor.Name]);
                  propertyDescriptor.SetValue(bindingContext.Model, value);
                  return;
              }
              else 
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
    }
    

    What solved the problem was this line:

    ShortStrOra value = new ShortStrOra(values[propertyDescriptor.Name]);
    

    Without it the engine throws a CastException when tries to set a string value on my ShortStrOra type, but it dies silently and a null value is setted on the property.

    To use the custom model binder in controller:

    [HttpPost]
    public ActionResult EditMember([ModelBinder(typeof(TesteModelBinder2))]TesteModel model)
        {
            return View("Index", model);
        }
    
    0 讨论(0)
提交回复
热议问题