2012-09-25 2 views
0

I 클래스 아래에 있습니다체크 박스 목록이

public class ControllerSecurityModel 
{ 
    public string ControlleName { get; set; } 
    public string DisplayName { get; set; } 
    public List<ActionSecurityModel> actions { get; set; } 
} 
public class ActionSecurityModel 
{ 
    public string ActionName { get; set; } 
    public string DisplayName { get; set; } 
    public bool IsChecked { get; set; } 
} 

및 모델 :

나는 각 "ActionSecurityModel"의 체크 박스를 갖고 싶어
public class PageRoleModel 
{ 
    public List<ControllerSecurityModel> AllPages { get; set; } 

    public List<ControllerSecurityModel> SelectedPage { get; set; } 
} 

, 나는 아래 쓰기 보기 :

<% using (Html.BeginForm()) 
    {%> 
<% foreach (var cont in Model.AllPages) 
    {%> 
<fieldset> 
    <legend> 
     <%= cont.DisplayName %></legend> 
    <% foreach (var act in cont.actions) 
     {%> 
    <%: Html.CheckBoxFor(x => act.IsChecked) %> 
    <%: Html.Label(act.DisplayName) %> 
    <% } %> 
</fieldset> 
<% } %> 
<input type="submit" value="save"/> 
<% } %> 

이 내 컨트롤러 조치 :

public ActionResult SetRole() 
    { 
     PageRoleModel model = new PageRoleModel(); 

     return View(model); 
    } 

    [HttpPost] 
    public ActionResult SetRole(PageRoleModel model) 
    { 
     return View(model); 
    } 

하지만 양식을 제출하면 모델이 null입니까? 확인란을 제출하고 저장하려면 어떻게해야합니까? 이처럼

답변

4

: 내 솔루션이 작동하고 있지 왜

<% using (Html.BeginForm()) { %> 
    <% for (var i = 0; i < Model.AllPages.Count; i++) { %> 
    <fieldset> 
     <legend> 
      <%= Model.AllPages[i].DisplayName %> 
     </legend> 
     <% for (var j = 0; j < Model.AllPages[i].actions.Count; j++) { %> 
      <%= Html.CheckBoxFor(x => x.AllPages[i].actions[j].IsChecked) %> 
      <%= Html.Label(Model.AllPages[i].actions[j].DisplayName) %> 
     } 
    </fieldset> 
    <% } %> 
    <input type="submit" value="save"/> 
<% } %> 

이해하려면, 기본 모델 바인더 컬렉션에 사용하는 것으로 wire format 읽어 보시기 바랍니다. 그런 다음 생성 된 HTML 소스 코드를 탐색하여 양식 입력 필드의 생성 된 이름을 확인하십시오. 그러면 체크 박스의 name 속성에 근본적인 차이점이 빠르게 나타납니다.

또한 POST 액션에서 전체 모델 바인딩을 기대하지 마십시오. 폼에는 입력란 하나만 있습니다. 확인란입니다. 따라서 서버로 전송되어 모델에 바인딩되는 유일한 값입니다. 당신이 다른 값을 필요한 경우뿐만 아니라 당신은 숨겨진 필드로를 포함 할 수있다 :

<!-- in the outer loop: --> 
<% =Html.HiddenFor(x => x.AllPages[i].DisplayName) %> 
... 
<!-- and then in the inner loop --> 
<%= Html.HiddenFor(x => x.AllPages[i].actions[j].ActionName) %> 
<%= Html.HiddenFor(x => x.AllPages[i].actions[j].DisplayName) %> 
... and so on ... 

이 또한 내가 매우 강력 편집기 템플릿을 사용하는 대신 귀하의 의견에 그 루프를 작성하는 당신에게 추천 할 것입니다. 자동으로 입력 필드의 적절한 이름을 생성하므로 걱정할 필요가 없습니다. 나는이 주제에 대한 답을 많이 가지고있다. 그냥 Google 내 이름과 검색에 editor templates asp.net mvc을 추가하면 많은 결과를 얻을 수 있습니다.

+0

고맙습니다. – Shayan

관련 문제