Asp.net mvc 4 获取多个复选框选择并用逗号分隔
我有一个权限列表,希望使用复选框选择权限,并在创建角色时传递所选复选框权限ID。 模型Asp.net mvc 4 获取多个复选框选择并用逗号分隔,asp.net-mvc-4,checkbox,Asp.net Mvc 4,Checkbox,我有一个权限列表,希望使用复选框选择权限,并在创建角色时传递所选复选框权限ID。 模型 我建议创建视图模型来表示要显示和编辑的数据 查看模型(根据需要添加验证属性) 看法 @model RoleVM @使用(Html.BeginForm()) { .... @Html.LabelFor(m=>m.Name)//不确定CustomLabel在做什么,但似乎没有必要 @Html.TextBoxFor(m=>m.Name) @Html.ValidationMessageFor(m=>m.Name) @
我建议创建视图模型来表示要显示和编辑的数据 查看模型(根据需要添加验证属性) 看法
@model RoleVM
@使用(Html.BeginForm())
{
....
@Html.LabelFor(m=>m.Name)//不确定CustomLabel在做什么,但似乎没有必要
@Html.TextBoxFor(m=>m.Name)
@Html.ValidationMessageFor(m=>m.Name)
@LabelFor(m=>m.Description)
@Html.TextBoxFor(m=>m.Description)
@Html.ValidationMessageFor(m=>m.Description)
@对于(int i=0;im.Permissions[i].IsSelected)
@Html.LabelFor(m=>m.Permissions[i].Name)
@Html.HiddenFor(m=>m.Permissions[i].ID)//用于回发
}
}
代码更少,无需javascript,更灵活地添加适合视图的显示和验证属性…您面临的问题在哪里,不清楚您在iti中面临的问题我不知道如何获取复选框中选定的ids值,并以字符串形式将其传递,并用逗号分隔。它们将在
Role-Role
action参数中的模型中发布。我可以举个例子多个问题1)您将ViewModelRole
传递到视图,但是,如果将POST方法参数更改为ViewModelRole
,则发回接受Role
2)的方法时,它仍将抛出异常,因为ViewModelRole
没有无参数构造函数。3) 您有多个名为no margin
的复选框,这些复选框与您的模型属性名称没有关系,并且它们都具有相同的id
,这是无效的html。创建视图模型以表示要显示/编辑的内容
public class RoleInsert
{
[Key]
public int RoleId { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public string Permission { get; set; }
}
view model
public class ViewModelRole
{
public int RoleId { get; set; }
public Role Role { get; set; }
public IEnumerable<RoleList> RoleList { get; set; }
public RoleInsert RoleInsert { get; set; }
public Permission Permission { get; set; }
public List<Permission> PermissionsList { get; set; }
//public IEnumerable<Role> IRole { get; set; }
public IDictionary<string, string> DynamicLabel;
private PreFlightDbContext preFlightDbContext;
private IRoleService roleService;
private readonly ILabelService labelService;
private int UserId;
}
}
view
@model PreFlight.ViewModels.ViewModelRole
@using PreFlight.Helpers
@{HtmlHelpers.getDynamicLabels(Model.DynamicLabel);}
<script type="text/javascript">
$(document).ready(function() {
$('#btn-gn').click(function () {
var list = [];
$('#MyDiv input:checked').each(function() {
list.push(this.name);
});
// now names contains all of the names of checked checkboxes
// do something with it for excamle post with ajax
$.ajax({
url: '@Url.Action("Create","Role")',
type: 'POST',
data: { Parameters: list},
success: function (result) {
alert("success");
},
error: function (result) {
alert("error!");
}
}); //end ajax
});
});
</script>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="dialogModal_header">
@Html.CustomLabel("lblTitle","Add New Role")
</div>
<div class="dialogModal_content">
<div class="group-form">
@Html.CustomLabel("lblRoleName","Role Name")
@Html.EditorFor(m => m.Role.RoleName)
@Html.ValidationMessageFor(m => m.Role.RoleName)
</div>
<div class="group-form1">
<div class="group-form2">
@Html.CustomLabel("lblDescription","Description")
@Html.TextAreaFor(m => m.Role.Description)
@Html.ValidationMessageFor(m => m.Role.Description)
</div>
</div>
<div class="main-content">
<div class="permissions-hd">
@Html.CustomLabel("lblPermissions","Permissions")
</div>
<div id="MySelection">
@for (int i = 0; i < Model.PermissionsList.Count; i++)
{
<div class="permissions">
<div class="cb">
<input type="checkbox" name="tags" class="no-margin"
id="=ids" value="@Model.PermissionsList[i].PermissionId" >
</div>
<div class="per-content">
@Model.PermissionsList[i].PermissionName</div>
</div>
}
</div>
</div>
</div>
<div class="dialogModal_footer">
@{
var s = Model.DynamicLabel.ContainsKey("btnSubmit") ? Model.DynamicLabel["btnSubmit"].ToString() : " Submit";
}
<button type="submit" id="btn-gn">@s</button>
@{
var c = Model.DynamicLabel.ContainsKey("btnClear") ? Model.DynamicLabel["btnClear"].ToString() : " Clear";
}
<button type="reset" id="btn-rd">@c</button>
</div>
}
public ActionResult Create()
{
ViewModelRole viewModelRole = new ViewModelRole();
viewModelRole.PermissionsList = preDbContext.Permissions.ToList();
return View(viewModelRole);
}
[HttpPost]
public ActionResult Create(ViewModelRole viewModelRoleForAdd, string rolename,string roledescription,string[] tags)
{
viewModelRoleForAdd.RoleInsert.RoleName = rolename;
viewModelRoleForAdd.RoleInsert.Description = roledescription;
viewModelRoleForAdd.RoleInsert.Permission = tags[];
Session[ApplicationConstants.CurrentPageId] = 130;
PreCoreModel.User loggedInUser = new PreCoreModel.User();
int PageId = Convert.ToInt16(Session[ApplicationConstants.CurrentPageId]);
if (Session[ApplicationConstants.UserModel] != null)
{
loggedInUser = (PreCoreModel.User)Session[ApplicationConstants.UserModel];
}
if (loggedInUser.UserId > 0)
{
ViewModelRole viewModelRole = new ViewModelRole(preDbContext, loggedInUser.UserId, PageId);
roleService.AddRole(rolename,roledescription,tags[]);
return View(viewModelRole);
}
else
{
return RedirectToAction("SignIn", "Account", new { area = "" });
}
}
public class PermissionVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class RoleVM
{
[Display(Name = "Role Name")]
public string Name { get; set; }
public string Description { get; set; }
public List<PermissionVM> Permissions { get; set; }
}
public ActionResult Create()
{
RoleVM model = new RoleVM();
model.Permissions = preDbContext.Permissions
.Select(p => new PermissionVM()
{
ID = p.PermissionId,
Name = p.PermissionName
});
return View(RoleVM);
}
[HttpPost]
public ActionResult Create(RoleVM model)
{
if(!ModelState.IsValid)
{
return View(model);
}
// Initialize your data model
// Map properties from the view model (loop model.Permissions to get the the selected permissions (IsSelected = true)
// Save and redirect
}
@model RoleVM
@using (Html.BeginForm())
{
....
@Html.LabelFor(m => m.Name) // Not sure what CustomLabel is doing but seems unnecessary
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
@Html.LabelFor(m => m.Description)
@Html.TextBoxFor(m => m.Description)
@Html.ValidationMessageFor(m => m.Description)
@for (int i = 0; i < Model.Permissions.Count; i++)
{
<div class="permission">
@Html.CheckBoxFor(m => m.Permissions[i].IsSelected)
@Html.LabelFor(m => m.Permissions[i].Name)
@Html.HiddenFor(m => m.Permissions[i].ID) // for post back
</div>
}
<input type="submit" value="Save" />
}