2012-03-13 58 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 : 

我怎樣才能從視圖中選中複選框(S)?

回答

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 2012-03-13 11:24:21

相關問題