简体   繁体   English

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

[英]Retrieving dynamic checkbox values and label from strongly typed view in MVC3

EDIT: whoever fixed my question so the code displayed right, thank you! 编辑:谁解决了我的问题,以便代码正确显示,谢谢! :) :)

I have a silly problem I really need som help with, after a whole day of googling I'm close to loosing my head! 我有一个很愚蠢的问题,我确实需要一点帮助,在搜索了整整一天之后,我几乎要失去头了!

I am working with the asp.net membership, and I want to be able to set roles on user once the web app is upp and running. 我正在使用asp.net成员身份,并且我希望能够在网络应用程序启动并运行后为用户设置角色。

To implement this I am sending a model to a strongly typed view with a list of checkboxes, if the user is in one of the roles in the list the checkbox is checked. 为了实现这一点,我将模型发送到带有复选框列表的强类型视图,如果用户处于列表中的角色之一,则选中该复选框。 (this part works) (这部分有效)

But I cant figure out how to return the checkbox values in the Edit method, as the model returns 'null' on the List-property. 但是我无法弄清楚如何在Edit方法中返回复选框值,因为模型在List属性上返回了“ null”。

I am sure I've missed something obvious here, and would be very happy for any help... 我敢肯定,我在这里错过了一些明显的事情,并且会很高兴获得任何帮助...

And how can I add code to this question? 以及如何向该问题添加代码? I cant get the formatting right... 我无法正确格式化...

View 视图

@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>

Controller 控制者

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");
}

Models 楷模

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; }
    }
}

It's really simple. 真的很简单。 You must give your checkboxes a name let's say myCheckboxes and you pass a int[] myCheckboxes to POST action. 您必须给您的复选框起个名字,比如说myCheckboxes,然后将int [] myCheckboxes传递给POST操作。 I've provided you a code sample: 我为您提供了一个代码示例:

In your view let's say you have 在您看来,假设您有

@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 />
}

Now to post what user has checked/unchecked you use the following: 现在要发布用户已选中/取消选中的内容,请使用以下命令:

[HttpPost]
public ActionResult Edit(UserRoleSaveVM saveRoles)
{ 

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

     }
  }

where UserRoleSaveVM is 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
}

At UserRoles.cs 在UserRoles.cs

Change 更改

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

to

public AllRolles[] AllRolles { get; set; }

At Edit.cshtml 在Edit.cshtml

Change 更改

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

to

@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)  
}

At your controller 在您的控制器

Add .ToArray() after UserActiveRoles(u.UserName) UserActiveRoles(u.UserName)之后添加.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);
}

The problem 问题

You must show to the ModelBinder that you're sending a collection, instead of a bunch of parameters. 您必须向ModelBinder显示正在发送集合,而不是一堆参数。

What's sent to the server? 什么发送到服务器?

AllRolles[0].IsActive:false AllRolles [0] .IsActive:false

AllRolles[0].Role:Admin AllRolles [0]。角色:管理员

AllRolles[1].IsActive:false AllRolles [1] .IsActive:false

AllRolles[1].Role:User AllRolles [1]。角色:用户

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM