2010-07-20 44 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