获取MVC 4中的复选框值 [英] Getting checked checkboxes value in MVC 4

查看:80
本文介绍了获取MVC 4中的复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图中有4个复选框,这些复选框是动态生成的,因为数据库中存在的值。所以在点击提交按钮时我想保存所有选中的复选框的值。请让我知道这方面的解决方案

I have 4 checkboxes in my view which are generated dynamically as for the values present in the database.So while clicking on submit button i want to save the values of the checkboxes which are all checked.PLease let me know solution for this

推荐答案

< input type =checkboxname =selectedRolesid =chkRolesvalue =@ role.RoleID>

@foreach(userRoles中的var userRole)

{

if(userRole.UserID == curID&& role.RoleID == userRole.RoleID)< br $>
{



isChecked2 = true;

@(Html.Raw(isChecked2?checked = \)已检查\:))

}

}

/>



如果您在运行时运行代码,请执行此操作名字字段将获得您选择的角色

然后将您的控制器写成这样的东西



[HttpPost]

[ValidateAntiForgeryToken]

public ActionResult Edit([Bind(Include =UserID,Name,Email)]用户用户,string [] selectedRoles,string userRoleID)

{< br $>




int s = Convert.ToInt32(user.UserID);



if(ModelState.IsValid)

{



foreach(selectedRoles中的var项目)

{

userRole.RoleID = Convert.ToInt32(item);



db.UserRole.Add(userRole);

db.SaveChanges();

}

}





ViewBag。 RoleID = new SelectList(db.Roles,RoleID,RoleName,user.RoleI D);

返回查看(用户);

}< / input>





或尝试断开链接



http://www.asp.net/mvc/tutorials / get-started-with-ef-5-using-mvc-4 / read-related-data-with-the-entity-framework-in-an-asp-mvc-application [ ^ ]
<input type="checkbox" name="selectedRoles" id="chkRoles" value="@role.RoleID">
@foreach (var userRole in userRoles)
{
if (userRole.UserID == curID && role.RoleID == userRole.RoleID)
{

isChecked2=true;
@(Html.Raw(isChecked2 ? "checked=\"checked\"" : ""))
}
}
/>

In this if you run the code at runtime name field will get your selected roles
then write your controller as something like this

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "UserID,Name,Email")] User user, string[] selectedRoles,string userRoleID)
{


int s=Convert.ToInt32(user.UserID);

if (ModelState.IsValid)
{

foreach (var item in selectedRoles)
{
userRole.RoleID = Convert.ToInt32(item);

db.UserRole.Add(userRole);
db.SaveChanges();
}
}


ViewBag.RoleID = new SelectList(db.Roles, "RoleID", "RoleName", user.RoleID);
return View(user);
}</input>


or try dis link

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application[^]


希望这些帮助:

1 。 get-checkbox-values-in-controller-mvc-4 [ ^ ]

2. get-multiple-selected-checkboxes-in-mvc [ ^ ]
Hope these help:
1. get-checkbox-values-in-controller-mvc-4[^]
2. get-multiple-selected-checkboxes-in-mvc[^]


这是一个简单的解释例子,可以帮助你

点击这里
Here's a simple example with explaination which might help you
click here


这篇关于获取MVC 4中的复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆