2009-04-03 2 views
7

사용자 지정 모델 바인더를 쓰려고하는데 복잡한 복합 개체를 바인딩하는 방법을 찾는 데 어려움을 겪고 있습니다. 복잡한 복합 개체 용 사용자 지정 모델 바인더 HELP

내가 바인딩려고하는 클래스입니다 :

public class Fund 
{ 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public List<FundAllocation> FundAllocations { get; set; } 
} 

이 사용자 정의 바인더를 작성에서 내 시도는 모습입니다 같은 :

public class FundModelBinder : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     throw new NotImplementedException(); 
    } 

    public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState) 
    { 
     var fund = new Fund(); 

     fund.Id = int.Parse(controllerContext.HttpContext.Request.Form["Id"]); 
     fund.Name = controllerContext.HttpContext.Request.Form["Name"]; 

     //i don't know how to bind to the list property :(
     fund.FundItems[0].Catalogue.Id = controllerContext.HttpContext.Request.Form["FundItem.Catalogue.Id"]; 
     return fund; 
    } 
} 

어떤 아이디어

감사합니다 토니

+0

방금 ​​질문을 올린 다음 결국 동일한 유형의 문제에 대한 해결책을 찾았습니다. 관심있는 사람들을 위해 아래 링크를 확인해보십시오. [http://stackoverflow.com/questions/1077481/how-do-i-pass-a-dictionary-as-a-parameter-to-an-actionresult -method-from-jquery-a] (http://stackoverflow.com/questions/1077481/how-do-i-pass-a-dictionary-as-a-parameter-to-an-actionresult-method-from- jquery-a) –

답변

3

나는이 정확한에 너무 많은 지출되었습니다 요즘 요!

HTML 폼을 보지 않고 멀티 선택 목록 또는 다른 선택 결과를 반환하는 것일뿐입니다. 그렇다면 양식은 수분이 가득한 FundAllocations 개체를 반환하는 대신 여러 개의 정수를 반환합니다. 그렇다면 사용자 정의 ModelBinder에서 직접 조회를 수행하고 객체를 스스로 수화해야 할 것입니다. 같은

뭔가 : 물론

fund.FundAllocations = 
     repository.Where(f => 
     controllerContext.HttpContext.Request.Form["FundItem.Catalogue.Id"].Contains(f.Id.ToString()); 

, 내 LINQ는 예를 들어 그리고 당신은 분명히 당신이 원하는 어쨌든 데이터를 검색 할 수 있습니다. 덧붙여 말하지만, 당신의 질문에 대답하지 않는다는 것을 알고 있지만 복잡한 객체의 경우 ViewModel을 사용하고 기본 ModelBinder를 바인드 한 다음 필요한 경우 수화를 결정하는 것이 좋습니다. 내 개체를 나타내는 모델입니다. 제가이 문제를 최우선 적으로 선택한 이유는 여러 가지입니다. 지금은 그들과 함께 지루하지 않을 것이지만, 원한다면 외삽 할 수는 있습니다.

최신 Herding Code podcastK Scott Allen's Putting the M in MVC blog posts과 같이 이에 대한 훌륭한 토론입니다.

8

여기에 사용자 정의 ModelBinder를 구현해야합니까? 기본 바인더 (이 컬렉션과 복잡한 객체를 채울 수있는) 당신이 필요로하는 일을 할 수

는 컨트롤러의 동작은 다음과 같습니다 말할 수 있습니다 :

public ActionResult SomeAction(Fund fund) 
{ 
    //do some stuff 
    return View(); 
} 

을 그리고 당신은 HTML이 포함

<input type="text" name="fund.Id" value="1" /> 
<input type="text" name="fund.Name" value="SomeName" /> 

<input type="text" name="fund.FundAllocations.Index" value="0" /> 
<input type="text" name="fund.FundAllocations[0].SomeProperty" value="abc" /> 

<input type="text" name="fund.FundAllocations.Index" value="1" /> 
<input type="text" name="fund.FundAllocations[1].SomeProperty" value="xyz" /> 

기본 모델 바인더는 FundAllocations List의 2 개 항목으로 자금 개체를 초기화해야합니다 (FundAllocation 클래스의 모양을 모르므로 하나의 속성 "SomeProperty"를 구성했습니다). 그냥 "fund.FundAllocations.Index"요소 (기본 바인더가 자신의 용도로 사용하는 것)를 포함시켜야합니다.이 요소는이 기능을 얻으려고 할 때 저를 잡았습니다.)

+0

JonoW - 표준 모델 바인더에 대한 좋은 문서를위한 링크가 있습니까? 아니면 원본을 보았습니까? –

+0

죄송합니다. 어떤 공식 문서에 대한 링크가 없으므로 필자는 비슷한 문제가 있었기 때문에 Phil Haack의 조언을 블로그에 올리고있었습니다. http://haacked.com/archive/2008/10 /23/model-binding-to-a-list.aspx. 1.0에서 할 수있는 더 좋은 방법이 있을지 모르지만 ... – JonoW

+0

그는 맞습니다. 사용자 정의 모델 바인더가 필요하지 않습니다. 위에서 설명한 것처럼 이름 필드를 조작하여이 작업을 수행 할 수 있습니다. – MedicineMan