你必須給你的複選框的名字:
@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>
}
感謝達林..這是什麼我想完成... – user1266244 2012-03-13 11:24:21