MVC Custom type property is not binding in my model

纵饮孤独 提交于 2019-12-01 06:33:32

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