运行ActionResult时,模型值为null

时间:2014-07-31 11:08:49

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

我在名为RoleController的控制器中有以下ActionResult

[HttpPost]
public ActionResult UsersForRole(RoleModel roleModel)
{
    if (ModelState.IsValid)
    {
        _roleService.AssignUsersToRole(roleModel.Users, roleModel);
    }
    return View(roleModel);
}

当我在视图中按保存(从少数几种形式之一)时,模型的参数都为空。

此页面的想法有2个列表框 - model.Users(分配给角色的用户列表)和model.UsersNotInRole(未分配给所选角色的用户列表)。

视图显示正确,当我按提交时,我需要运行_roleService.AssignUsersToRole(),如控制器中所示。

RoleModel.cs

public class RoleModel
{
    public int Id { get; set; }
    public string RoleName { get; set; }
    public string Description { get; set; }
    public DateTime DateCreated { get; set; }
    public int CreatedBy { get; set; }
    public DateTime LastUpdated { get; set; }
    public int LastUpdateBy { get; set; }

    [NotMapped]
    public State State { get; set; }

    public virtual List<UserModel> Users { get; set; }
    public virtual List<UserModel> UsersNotInRole { get; set; }

    public virtual List<RightModel> Rights { get; set; }

    public List<UserModel> SelectedUsersNotInRole { get; set; }
    public List<UserModel> SelectedUsers { get; set; }

    public RoleModel()
    {
        Users = new List<UserModel>();
        SelectedUsersNotInRole = new List<UserModel>();
        SelectedUsers = new List<UserModel>();
    }
}

Screenshot of roleModel

为什么会发生这种情况?

查看(Details.cshtml)

@model Application.Core.Models.Roles.RoleModel
<div class="tab-pane" id="tab_1_2">
    @using (Html.BeginForm("UsersForRole", "Role", FormMethod.Post, new { }))
    {
        @Html.ValidationSummary(true)    
        <!-- BEGIN DUAL SELECT-->
        @Html.ListBoxFor(m => m.UsersNotInRole, new SelectList(Model.UsersNotInRole), new {@style = "width: 75%; height: 300px;"})

        @Html.ListBoxFor(m => m.Users, new SelectList(Model.Users), new {@style = "width: 75%; height: 300px;"})

        <input type="submit" value="Submit" class="btn" />
    }
</div>

2 个答案:

答案 0 :(得分:0)

添加到RoleModel:

public UsersNotInRoleType SelectedUsersNotInRole {get; set;}
public UsersType SelectedUsers {get; set;}

在视图中替换:

@Html.ListBoxFor(m => m.SelectedUsersNotInRole , new SelectList(Model.UsersNotInRole), new {@style = "width: 75%; height: 300px;"})

@Html.ListBoxFor(m => m.SelectedUsers , new SelectList(Model.Users), new {@style = "width: 75%; height: 300px;"})

答案 1 :(得分:0)

基本上你需要两个系列。为了简单起见,我们只关注一个列表框(另一个列表框的概念相同)。如果我们采用model.Users本质上你有'Users'属性来填充你的列表框。但是,您需要另一个集合(例如SelectedUsers)来存储您的选择。然后在你的视图中,你将把

@Html.ListBoxFor(m => m.SelectedUsers , new SelectList(Model.Users), new {@style = "width: 75%; height: 300px;"})

在您的帖子操作结果中,您需要将SelectedUsers(而不是用户)传递到_roleService.AssignUsersToRole

Youtube Video会帮助您