从MVC3中的强类型视图中检索动态复选框值和标签

时间:2012-03-23 21:17:19

标签: c# asp.net-mvc asp.net-mvc-3

编辑:谁解决了我的问题所以代码显示正确,谢谢! :)

我有一个愚蠢的问题,我真的需要帮助,经过一整天的谷歌搜索,我几乎要失去理智了!

我正在使用asp.net会员资格,我希望能够在网络应用程序运行并运行后为用户设置角色。

为了实现这一点,我将模型发送到带有复选框列表的强类型视图,如果用户位于列表中的一个角色中,则选中该复选框。 (这部分有效)

但是我无法弄清楚如何在Edit方法中返回复选框值,因为模型在List-property上返回'null'。

我确信我错过了一些明显的东西,并且非常乐意为你提供任何帮助......

如何在此问题中添加代码?我不能正确格式化......

查看

@model Mvc4m.Models.UserRoles
@{
    ViewBag.Title = "Edit";
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript">    </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>UserRoles</legend>

    <div class="editor-label">
        <h2> @Html.DisplayFor(model => model.Name)</h2>
    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.Roles)
    </div>
    <div class="editor-field" id="testar">

    @foreach (var model in Model.AllRolles)
    {
        @Html.CheckBoxFor(item => model.IsActive, model.Role)
        @Html.Label(model.Role)  
    }

    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.IsApproved)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.IsApproved)
        @Html.ValidationMessageFor(model => model.IsApproved)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

控制器

public List<AllRolles> UserActiveRoles(string name)
{
    var list = new List<AllRolles>();

    foreach(var role in Roles.GetAllRoles())
    {
        var hej = new AllRolles()
                      {
                          Role = role,
                          IsActive = Roles.IsUserInRole(name,role)
                      };
        list.Add(hej);
    }
    return list;
}

public ActionResult Index()
{
    var roles = Roles.GetAllRoles();
    var users = from MembershipUser u in Membership.GetAllUsers()
                select new UserRoles()
                {
                    Name = u.UserName,
                    AllRolles = UserActiveRoles(u.UserName)
                };
    return View(users);
}

public ActionResult Edit(string name)
{
    var user = Membership.GetUser(name);
    var model = new UserRoles()
    {
        Name = user.UserName,
        AllRolles = UserActiveRoles(name)
    };
    return View(model);
}

//
// POST: /Admin/ManageUsers/Edit/5

[HttpPost]
public ActionResult Edit(UserRoles user)
{
    var name = user.Name;

    foreach (var role in user.AllRolles)
    {
        if (role.IsActive == true)
            Roles.AddUserToRole(name,role.Role);
        else 
            Roles.RemoveUserFromRole(name,role.Role);
    }

    return RedirectToAction("Index");
}

模型

public class UserRoles
{
    public string Name { get; set; }

    public List<string> Roles { get; set; }

    public bool IsApproved { get; set; }

    public List<AllRolles> AllRolles { get; set; }

}

namespace Mvc4m.Areas.Admin.Models
{
    public class AllRolles
    {
        public string Role { get; set; }
        public bool IsActive { get; set; }
    }
}

2 个答案:

答案 0 :(得分:0)

这很简单。你必须给你的复选框一个名字让我们说myCheckboxes你将一个int [] myCheckboxes传递给POST动作。我已经为您提供了代码示例:

在你看来,假设你有

@foreach (var role in Model.AllRoles)
{
  <input type="checkbox" name="UserNotInRoles" value="@role.RoleId" checked/>@role.RoleName
  <br />
}

@foreach (var role in Model.UserRole)
{
  <input type="checkbox" name="UserInRoles" value="@role.RoleId" checked/>@role.RoleName    
  <br />
}

现在要发布用户已选中/取消选中的内容,请使用以下内容:

[HttpPost]
public ActionResult Edit(UserRoleSaveVM saveRoles)
{ 

  if (saveRoles.UserNotInRoles != null)
  {                
     foreach (int roleID in saveRoles.UserNotInRoles)
     {
        //DO SOMETHING

     }
  }

UserRoleSaveVM

public class UserRoleSaveVM
{
  public int UserID { get; set; }
  public int[] UserInRoles { get; set; } //note that property name is the same as checkbox name
  public int[] UserNotInRoles{ get; set; } //note that property name is the same as checkbox name
}

答案 1 :(得分:0)

在UserRoles.cs

更改

public List<AllRolles> AllRolles { get; set; }

public AllRolles[] AllRolles { get; set; }

在Edit.cshtml

更改

@foreach (var model in Model.AllRolles) 
{
    @Html.CheckBoxFor(item => model.IsActive, model.Role)
    @Html.Label(model.Role)  
}

@for (int i = 0; i < Model.AllRolles.Length; i++) 
{
    @Html.CheckBoxFor(item => Model.AllRolles[i].IsActive)
    @Html.HiddenFor(item => Model.AllRolles[i].Role)
    @Html.Label(Model.AllRolles[i].Role)  
}

在您的控制器

.ToArray()

之后添加UserActiveRoles(u.UserName)
public ActionResult Index()
{
    var roles = Roles.GetAllRoles();
    var users = from MembershipUser u in Membership.GetAllUsers()
            select new UserRoles()
            {
                Name = u.UserName,
                AllRolles = UserActiveRoles(u.UserName).ToArray()
            };
    return View(users);
}

问题

您必须向ModelBinder显示您正在发送一个集合,而不是一堆参数。

什么发送到服务器?

  

AllRolles [0] .IsActive:假

     

AllRolles [0]。角色:管理员

     

AllRolles [1] .IsActive:假

     

AllRolles [1]。角色:用户

希望有所帮助