发布ViewModel列表

时间:2018-04-20 00:25:55

标签: c# asp.net-core

我想从特定用户提交角色列表,表单有开关(android风格)(开/关),并且在发布后控制器没有值。

我认为错误是因为我希望从View上的Vm列表中接收值。

但我不知道我将如何做到这一点。

带有用户信息的虚拟机(需要显示我正在编辑的记录)

namespace Inside.ViewModels.UsersViewModels
{
    public class RolesEditViewModel
    {
        [Display(Name = "ID")]
        public string UserId { get; set; }

        [Display(Name = "Nome")]
        public String UserFirstAndLastName { get; set; }

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

RolesIndexViewModel:

namespace Inside.ViewModels.UsersViewModels
{
    public class RolesIndexViewModel
    {
        [Display(Name = "ID")]
        public string Id { get; set; }

        [Required]
        [StringLength(64, ErrorMessage = "O campo {0} tem de ter pelo menos {2} e no maximo {1} characters.", MinimumLength = 2)]
        [Display(Name = "Nome")]
        public String Name { get; set; }

        [Display(Name = "Estado")]
        public bool RoleStatus { get; set; }
    }
}

查看

@using Inside.ViewModels.UsersViewModels

@model RolesEditViewModel

@{
    ViewData["Title"] = "Editar Permissões Utilizador";
}

<!-- ============================================================== -->
<!-- Container fluid  -->
<!-- ============================================================== -->
<div class="container-fluid">
    <!-- ============================================================== -->
    <!-- Bread crumb and right sidebar toggle -->
    <!-- ============================================================== -->
    <div class="row page-titles">
        <div class="col-md-5 align-self-center">
            <h3 class="text-themecolor">Editar Permissões</h3>
        </div>
        <div class="col-md-7 align-self-center">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a>Dashboard</a></li>
                <li class="breadcrumb-item active">Utilizadores</li>
                <li class="breadcrumb-item active">Editar Permissões</li>
            </ol>
        </div>
        <div class="">
            <button class="right-side-toggle waves-effect waves-light btn-inverse btn btn-circle btn-sm pull-right m-l-10"><i class="ti-settings text-white"></i></button>
        </div>
    </div>
    <!-- ============================================================== -->
    <!-- End Bread crumb and right sidebar toggle -->
    <!-- ============================================================== -->
    <!-- ============================================================== -->
    <!-- Page Content -->
    <!-- ============================================================== -->
    <div class="row">
        <div class="col-lg-12">
            <div class="card ">
                <div class="card-header bg-info">
                    <div class="row">
                        <div class="col-md-8">
                            <h4 class="m-b-0 text-white">Editar Permissões de Utilizador - @Model.UserFirstAndLastName</h4>
                        </div>

                    </div>
                </div>
                <div class="card-body">
                    <form asp-controller="Users" asp-action="EditRoles" asp-route-id="@Model.UserId" class="form-material m-t-40">
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                        <div class="form-body">
                            <h3 class="box-title">Permissões - @Model.UserFirstAndLastName</h3>
                            <hr class="m-t-0 m-b-40">

                            <div class="table-responsive">
                                <table id="demo-foo-addrow" class="table table-hover contact-list footable-loaded footable" data-page-size="50">
                                    <thead>
                                        <tr>
                                            <th class="footable-sortable">@Html.DisplayNameFor(model => model.Roles[0].Name)<span class="footable-sort-indicator"></span></th>
                                            <th class="footable-sortable">@Html.DisplayNameFor(model => model.Roles[0].RoleStatus)<span class="footable-sort-indicator"></span></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach (var role in Model.Roles)
                                        {
                                        <tr class="footable-even" style="">
                                            <td>@Html.DisplayFor(modelItem => role.Name)</td>
                                            <td>
                                                <div class="switchery-demo m-b-30">
                                                    <input type="checkbox" checked class="js-switch" data-color="#009efb" />
                                                </div>
                                            </td>
                                        </tr>
                                        }
                                    </tbody>
                                </table>
                            </div>

                        </div>
                        <hr>
                        <div class="form-actions">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="row text-right">
                                        <div class="col-md-offset-3 col-md-11">
                                            <button type="submit" class="btn btn-danger">Actualizar Registo</button>
                                            <a asp-controller="Users" asp-action="Details" asp-route-id="" class="btn btn-success">Cancelar</a>
                                            <a asp-controller="Users" asp-action="Index" class="btn btn-success">Voltar a Listagem</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>


    <!-- ============================================================== -->
    <!-- End Page Content -->
    <!-- ============================================================== -->
</div>
<!-- ============================================================== -->
<!-- End Container fluid  -->
<!-- ============================================================== -->
@section Scripts {
    <script>
    jQuery(document).ready(function() {
        // Switchery
        var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
        $('.js-switch').each(function() {
            new Switchery($(this)[0], $(this).data());
        });
    });
    </script>
}

控制器

   // POST: Users/EditRoles/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    //[Authorize(Roles = "UsersEditRolesPost")]
    public async Task<IActionResult> EditRoles(string id, [Bind("Id,Name,RoleStatus")] RolesEditViewModel vm)
    {
        if (String.IsNullOrEmpty(id))
        {
            return RedirectToAction("ErrorBadRequest", "Errors");
        }
        var userExists = _users.UserExists(id);
        if (!userExists.Item1)
        {
            return RedirectToAction("NotFound", "Errors", new { id = userExists.Item2 });
        }
        if (ModelState.IsValid)
        {
            await _users.UpdateUserRolesStatusAsync(id, vm);
            return RedirectToAction("Details", "Users", new { id = vm.UserId });
        }
        return View(vm);
    }

1 个答案:

答案 0 :(得分:0)

请尝试这种方式

查看:

   @for (var index = 0; index < Model.Roles.Count; index++)
    {
                                                    var role = Model.Roles[index];
                                                    <tr class="footable-even" style="">
                                                        <td>@Html.DisplayFor(modelItem => role.Name)</td>
                                                        <td>
                                                            <div class="switchery-demo m-b-30">
                                                                <input type="hidden" asp-for="@Model.Roles[index].Id"/>
                                                                <input type="hidden" asp-for="@Model.Roles[index].Name"/>
                                                                <input asp-for="@Model.Roles[index].RoleStatus" type="checkbox" checked class="js-switch" data-color="#009efb"/>
                                                            </div>
                                                        </td>
                                                    </tr>
}

控制器

    [HttpPost]
    [ValidateAntiForgeryToken]
    //[Authorize(Roles = "UsersEditRolesPost")]
    public async Task<IActionResult> EditRoles(string id, RolesEditViewModel vm)
    {
        if (String.IsNullOrEmpty(id))
        {
            return RedirectToAction("ErrorBadRequest", "Errors");
        }
        var userExists = _users.UserExists(id);
        if (!userExists.Item1)
        {
            return RedirectToAction("NotFound", "Errors", new { id = userExists.Item2 });
        }
        if (ModelState.IsValid)
        {
            await _users.UpdateUserRolesStatusAsync(id, vm);
            return RedirectToAction("Details", "Users", new { id = vm.UserId });
        }
        return View(vm);
    }