2011-04-01 1 views
3

모델 바인더를 실제로 본적이 없으므로 여기에서 약간 손실됩니다. 가능한 경우 정확하게 제 문제에 대해 실제로 생각하고 있다면 조언 해 주시면됩니다. :) 그리고 내 코드가 도움이된다면 조언하십시오. 내 REPO/비즈니스 계층 내에서뷰에서 데이터를 가져 오는 중 모델 바인더를 사용해야하나요?

Public Class CustomFields 
{ 
public string Name {get;set;} 
public string Description {get;set;} 
public string FieldType {get;set;} 
public string Value {get;set;} 
} 

2 내가 값을 설정하고 반환하고 ..

1 -I은 이름이 '사용자 정의 필드'각각 다른 특성 즉 포함하는 DTO 클래스가 보기를 렌더링 할 ICollection

3-보기는 필드를 표시하기 위해 foreach를 사용합니다.

<% foreach (var item in Model) {%> 
    <div class="editor-label"> 
     <%= Html.Label(item.Name) %> 
    </div> 
    <div class="editor-field"> 
     <%= Html.TextBox(item.Name, item.Value)%> 
    </div> 
<% } %> 

질문 : 게시물을 통해 결과를 검색하는 가장 좋은 방법은 무엇입니까? 오류가 있으면 나는 ...보기에 오류를 다시 보내

주의가 필요합니다 내가 무슨 짓을 ->

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Index([ModelBinder(typeof(CustomModelBinder))] ICollection<CustomFields> Fields) 
{ 
//code here... 
} 

사용자 정의 모델 바인더를 가져 형태의 컬렉션에서 가치와 올바른로의 변환 이게 맞습니까? 이 작업을 수행하는 가장 좋은 방법은 무엇입니까? 나는 복잡한 것을 느낀다 ...

답변

3

뷰에서 foreach 루프를 언급하는 단계 3까지는 모든 것이 완벽합니다. 그것이 내가 대신 편집기 템플릿을 멈추고 사용할 수있는 곳입니다.

<%= Html.EditorForModel() %> 

하고 모델 콜렉션의 각 요소 (~/Views/Shared/EditorTemplates/CustomFields.ascx) 렌더링됩니다 해당 편집기 템플릿 내부 : 간단히

<div class="editor-label"> 
    <%= Html.LabelFor(x => x.Name) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.Name) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.Value) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.Description) %> 
</div> 
<div class="editor-field"> 
    <%= Html.TextBoxFor(x => x.FieldType) %> 
</div> 

:

그래서하여보기에서 루프를 교체
[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Index(IEnumerable<CustomFields> fields) 
{ 
    //code here... 
} 

모델 바인더가 필요하지 않습니다. 편집기 템플릿은 입력 필드의 올바른 이름을 생성하여 올바르게 바인딩되도록 처리합니다.

+0

감사합니다. 모델 편집자를 생각하지 마세요! :) – Haroon