2012-03-13 2 views
0

모델 :MVC3의 뷰에서 어떤 checbox가 선택되었는지 확인하는 방법은 무엇입니까?

public IEnumerable<Role> Roles { get; set; } 

지수 :

Roles = securityServiceClient.GetAllRoles() 

보기 :

@foreach (var role in Model.Roles) 
      { 
       <tr> 
        @if (role.Name == "User") 
        { 
         <td><input type="checkbox" checked="checked"/></td> 
        } 
        else 
        { 
         <td><input type="checkbox"/></td> 
        } 
        <td>@Html.Label(role.Name)</td> 
       </tr> 
      } 

[HttpPost] 
CreateSomething : 

가 어떻게 뷰에서 선택한 체크 박스 (들)을받을 수 있나요?

답변

2

당신은 당신의 체크 박스 이름을 제공해야합니다 : 다음

@if (role.Name == "User") 
{ 
    <td><input type="checkbox" checked="checked" name="roles"/></td> 
} 
else 
{ 
    <td><input type="checkbox" name="roles"/></td> 
} 

를 실행 한 다음, 당신이보기 모델, 강력한 형식의 뷰와 헬퍼를 사용하고 당신이 그랬던 것처럼 체크 박스를 하드 코딩하지되어야한다 또한

[HttpPost] 
public ActionResult Index(IEnumerable<string> roles) 
{ 
    ...  
} 

당신의 veiws.

모델 : 다음

public class MyViewModel 
{ 
    public RoleViewModel[] Roles { get; set; } 
} 

public class RoleViewModel 
{ 
    public string RoleName { get; set; } 
    public bool IsSelected { get; set; } 
} 

과 :

public class HomeController: Controller 
{ 
    public ActionResult Index() 
    { 
     var roles = securityServiceClient.GetAllRoles().Select(r => new RoleViewModel 
     { 
      RoleName = r.Name 
     }); 

     var model = new MyViewModel 
     { 
      Roles = roles 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(IEnumerable<RolesViewModel> roles) 
    { 
     ... 
    } 
} 

및 뷰에

가 :

@model MyViewModel 
@using (Html.BeginForm()) 
{ 
    <table> 
     <thead> 
      <tr> 
       <th>role</th> 
      </tr> 
     </thead> 
     <tbody> 
      @for (var i = 0; i < Model.Roles.Length; i++) 
      { 
       <tr> 
        <td> 
         @Html.CheckBoxFor(x => x.Roles[i].IsSelected) 
         @Html.LabelFor(x => x.Roles[i].IsSelected, Model.Roles[i].RoleName) 
         @Html.HiddenFor(x => x.Roles[i].RoleName) 
        </td> 
       </tr> 
      } 
     </tbody> 
    </table> 
} 
+0

감사 대린 ... 이것은 무엇을 여기있다

무슨 뜻인지입니다 나는 성취하고 싶다 ... – user1266244

관련 문제