2010-07-16 2 views
0

강력하게 형식화 된 ProductListingViewModel 유형의보기가 있으며이 ProductViewModel에는 ProductViewModel이 있습니다. (두 가지 사용자 정의보기 모델 모두).여러 객체가 포함 된 ViewModel에 대한 모델 바인딩

내 페이지에 어떤 형태의 요소를 가질 이들은 같은 만든 다음 HTML 생성

<%: Html.DropDownListFor(m => m.ProductViewModel.CategoryId, Model.Categories)%> 

: 내가 기대 바인딩 기본 모델

<select name="ProductViewModel.CategoryId" id="CategoryId"> 

를 그 난에 게시 할 때 ProductListModel.CategoryId를 관련 데이터로 채우는 것을 알고있는 ProductListingViewModel 유형의 매개 변수를 받아들이는 컨트롤러 액션.

선택 목록의 이름은 CategoryId 속성이있는 ProductViewModel이 있음을 나타내는 것으로 보이지만 컨트롤러 메서드에 게시하면 ProductViewModel이 null입니다. ProductListingViewModel을 생성하는 동안 이것을 생성하면 더 이상 null이 아니지만 기본 바인더는 예상대로 속성을 채우지 않는 것 같습니다.

커스텀 모델 바인더의 경우입니까, 아니면 뭔가 근본적인 것이 누락 되었습니까?

건배.

답변

1

요약하자면 (내가 잘못하면 나를 바로 잡으십시오).

모델 :

public class ProductListingViewModel 
{ 
    public ProductViewModel ProductViewModel { get; set; } 
    public IEnumerable<SelectListItem> Categories { get; set; } 
} 

public class ProductViewModel 
{ 
    public string CategoryId { get; set; } 
} 

컨트롤러 :

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new ProductListingViewModel 
     { 
      Categories = new SelectList(new[] 
      { 
       new { Value = "1", Text = "category 1" }, 
       new { Value = "2", Text = "category 2" } 
      }, "Value", "Text") 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(ProductListingViewModel model) 
    { 
     return View(model); 
    } 
} 

보기 : 양식을 제출할 때 지금

<% using (Html.BeginForm()) { %> 
    <%: Html.DropDownListFor(m => m.ProductViewModel.CategoryId, Model.Categories)%> 
    <input type="submit" value="OK" /> 
<% } %> 

당신이 얻을 것이다 :

model.ProductViewModel.CategoryId = the id that was selected in the drop down list 

당신이 뭘하고 있는거야?

+0

안녕하세요. 그것은 내가하는 일과 거의 동일 해 보입니다. 문제는 양식을 제출할 때 model.ProductViewModel이 null이라는 것입니다. ProductListModel을 ProductListingViewModel의 생성자에서 만들면 더 이상 null이 아니지만 게시 한 값이 하나도 포함되어 있지 않습니다. –

+0

제가 게시 한 것이 작동하기 때문에 문제가되는 것은 거의 동일합니다 *. –

+0

나는 당신의 예제와 정확히 똑같이 만들었지 만 여전히 null 값을 돌려 준다. 이상한. 나는 틀린 무엇인가하고있다. 그러나 나는 무엇이 확실하지 않다. –

0

이 경우 기본 바인더가 작동해야합니다.

클라이언트에서 보낸 데이터를 확인하기 위해 피들러를 사용해 보셨습니까?

정확히 컨트롤러 동작의 서명은 무엇입니까?

관련 문제