I asked about an issue I have with comma delimited numeric values here.
Given some of the replies, I attempted to try to implement my own model binder as follows:
[HttpPost]
public ActionResult Edit([ModelBinder(typeof(PropertyModelBinder))]PropertyModel model)
{
ModelState.Clear();
TryValidateModel(model);
if (ModelState.IsValid)
{
//Save property info.
}
return View(model);
}
Hope This will Help.
Also you can try @Ryan solution as well.
This could be your Custom ModelBinder. ( In this case you don't need to update your Edit Action Result As I suggested above)
public class PropertyModelBinder : DefaultModelBinder
{
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
if(propertyDescriptor.ComponentType == typeof(PropertyModel))
{
if (propertyDescriptor.Name == "Price")
{
var obj= bindingContext.ValueProvider.GetValue("Price");
return Convert.ToInt32(obj.AttemptedValue.ToString().Replace(",", ""));
}
}
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}
}
As you have updated your scope for binding. I have provided my suggestion in comments. Also if you use ModelBinder for Property and Agent than you can do like this.
//In Global.asax
ModelBinders.Binders.Add(typeof(Property), new PropertyRegistrationModelBinder());
ModelBinders.Binders.Add(typeof(Agent), new PropertyRegistrationModelBinder());
//Updated ModelBinder look like this.
public class PropertyRegistrationModelBinder : DefaultModelBinder
{
protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
if (propertyDescriptor.ComponentType == typeof(Property) || propertyDescriptor.ComponentType == typeof(Agent))
{
if(propertyDescriptor.Name == "Price" || propertyDescriptor.Name == "AnnualSales")
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue.Replace(",", string.Empty);
return string.IsNullOrEmpty(value) ? 0 : Convert.ToInt32(value);
}
}
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}
}
Also I would like to say that you are able to find many information related to this and also you can do same thing many ways. Like if you introduce new attribute that apply to class property for binding same way you apply ModelBinder at class level.