2010-07-20 43 views
2

我有以下选择列表:asp.net的MVC 2 - 模型绑定并选择列表

<select d="Owner_Id" name="Owner.Id"> 
    <option value="">[Select Owner]</option> 
    <option value="1">Owner 1</option> 
    <option value="2">Owner 2</option> 
    <option value="3">Owner 3</option> 
</select> 

它被绑定到:

public class Part 
{ 
    // ...other part properties... 
    public Owner Owner {get; set;} 
} 

public class Owner 
{ 
    public int Id {get; set;} 
    public string Name {get; set;} 
} 

我遇到的问题是,如果[Select Owner]选项被选中,然后抛出一个错误,因为我将一个空字符串绑定到一个int。我想要的行为是一个空字符串,只会导致Part上的一个空的Owner属性。

有没有办法修改零件模型联编程序来获得这种行为?所以,当绑定Part的Owner属性时,如果Owner.Id是一个空字符串,那么只需返回一个null Owner。我不能修改所有者模型联编程序,因为我需要在其控制器中添加/删除所有者的默认行为。

回答

1

你可以尝试自定义模型粘合剂:

public class PartBinder : DefaultModelBinder 
{ 
    protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) 
    { 
     if (propertyDescriptor.PropertyType == typeof(Owner)) 
     { 
      var idResult = bindingContext.ValueProvider 
       .GetValue(bindingContext.ModelName + ".Id"); 
      if (idResult == null || string.IsNullOrEmpty(idResult.AttemptedValue)) 
      { 
       return null; 
      } 
     } 
     return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); 
    } 
} 

然后:

[HttpPost] 
public ActionResult Index([ModelBinder(typeof(PartBinder))]Part part) 
{ 
    return View(); 
} 

或全局注册它:

ModelBinders.Binders.Add(typeof(Part), new PartBinder()); 
+0

完美,谢谢。 – anonymous 2010-07-20 19:21:54