Wednesday, March 16, 2011

Overlooked property getter on custom Model Binder of ASP.NET MVC will make your property unavailable on BindProperty method

If your custom property binder is not invoked on BindProperty method, chances are that you forgot to include a getter for your property. Though in my code's case, I remove the getter in purpose, so the consuming programmer cannot accidentally use the raw submitted values.

This code ...

[BindingName("show_field")]
public string ShowFieldRaw 
{ 
   set 
   { 
       _showFieldRaw = value; 
       ShowFields = _showFieldRaw.Split(','); 
   }  
}


...won't get invoked on BindProperty:

public class PropertyBinder : DefaultModelBinder
{

 protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
 {
  base.BindProperty(controllerContext, bindingContext, propertyDescriptor);

  /* if (propertyDescriptor.Name == "ShowFieldRaw")
   throw new Exception(controllerContext.HttpContext.Request["show_field"]); */
  
  foreach (var p in propertyDescriptor.Attributes)
  {
   if (p.GetType() == typeof(BindingNameAttribute))
   {
    var b = p as BindingNameAttribute;
    object value = controllerContext.HttpContext.Request[b.Name];
    

    if (propertyDescriptor.PropertyType == typeof(int))
     propertyDescriptor.SetValue(bindingContext.Model, Convert.ToInt32(value));
    else
     propertyDescriptor.SetValue(bindingContext.Model, value);

    break;
   }
  }//foreach
  
 }
}// class PropertyBinder

So you must modify your model and put a getter on the property to make that property be included on BindProperty method:

[BindingName("show_field")]
public string ShowFieldRaw 
{ 
    set 
    { 
        _showFieldRaw = value; ShowFields = _showFieldRaw.Split(','); 
    } 
    get 
    { 
        return _showFieldRaw; 
    }  
}


Related to error on jQuery AJAX Combobox I debugged: http://code.google.com/p/asp-net-mvc-backed-jquery-ajax-combobox/downloads/list

No comments:

Post a Comment