2012-03-13 4 views
0

モデル:どのchecboxがMVC3のビューでチェックされているかを確認する方法は?

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

関連する問題