2010-07-20 1 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의 null Owner 속성이 결과로 나타납니다.

이 동작을 위해 부품 모델 바인더를 수정하는 방법이 있습니까? 그래서 Part의 Owner 속성을 바인딩 할 때 Owner.Id가 빈 문자열이면 null Owner 만 반환합니다. 자체 컨트롤러 (소유자 추가/제거)에서 기본 동작을 필요로하므로 소유자 모델 바인더를 수정할 수 없습니다.

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

또는 전 세계적으로 등록합니다 : 다음

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); 
    } 
} 

과 :

답변

1

사용자 정의 모델 바인더를 시도 할 수

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

완벽, 감사합니다. – anonymous