簡體   English   中英

將ViewModel值傳遞給按鈕或ActionLink單擊上的MVC Controller操作方法

[英]Passing ViewModel values to MVC Controller action method on button or ActionLink click

我有一個帶幾個下拉菜單的asp.net/razor頁面,我嘗試創建一個按鈕或操作鏈接,該按鈕或操作鏈接在“ AccountController”類中調用名為“ AssignRole”的方法,並將下拉菜單中選擇的值傳遞給該方法。 我一直在嘗試各種方法,但沒有一種能正常工作:

    @model SpecSelRepos.Models.AccountViewModels.ManageRolesViewModel

    <fieldset>
        <label for="selectUserName">Users:</label>
        <select asp-for="ManageRolesUser" asp-items="Model.Users"></select>
        &nbsp;
        <label for="selectRoleName">Roles:</label>
        <select asp-for="ManageRolesRole" asp-items="Model.Roles"></select>
        &nbsp;

        @*button 1*@
        @using (Html.BeginForm("AssignRole", "Account"))
        {
            <input type="submit" value="Add User to Role" name="buttonAddUserToRole">


         }

        @*button 2*@
        <button class="btn btn-info" type="button" name="assignRole" onclick="location.href='@Url.Action("AssignRole", "Account", new { email = Model.ManageRolesUser, role = Model.ManageRolesRole })'"></button>

        @*link 1*@
        @Html.ActionLink("Assign Role", "AssignRole", "Account", new { email = Model.ManageRolesUser, role = Model.ManageRolesRole }, null)

        @*link 2*@
        @Html.ActionLink("Assign Role", "AssignRole", "Account", new { email = Model.ManageRolesUser, role = Model.ManageRolesRole })

    </fieldset>

在AccountController類中,我具有以下操作方法:

public async Task<IActionResult> AssignRole(string email, string role)
        {
            ApplicationUser user = GetUserByEmail(email);
            if(null == user)
            {
                return Content("No user with given email:" + email);
            }
            // if the role exists, assign the role to the user
            if (await _roleManager.RoleExistsAsync(role))
            {
                if(!await _userManager.IsInRoleAsync(user, role))
                {
                    await _userManager.AddToRoleAsync(user, role);
                    return Content("Role assigned: " + GetUserRoles(user));
                }
                else
                {
                    return Content ("User is in role: " + role + ": " + GetUserRoles(user));
                }
            }
            else
            {
                return Content("Role: " + role + " does not exist");
            }
        }

單擊按鈕1沒有明顯的作用。 按鈕2和兩個鏈接似乎都調用了AssignRole方法,但是所有3個鏈接都拋出空值錯誤:

ArgumentNullException: Value cannot be null.
 Parameter name: email
Microsoft.AspNetCore.Identity.UserManager.FindByEmailAsync(string email)
SpecSelRepos.Controllers.AccountController.GetUserByEmail(string email) in AccountController.cs
+                return _userManager.FindByEmailAsync(email).Result;
SpecSelRepos.Controllers.AccountController+<AssignRole>d__10.MoveNext() in AccountController.cs
+                ApplicationUser user = GetUserByEmail(email);

因此,似乎該方法已按需要被調用,但視圖模型中的值將作為null而不是在下拉框中選擇的值進行傳遞。

這是視圖模型類:

public class ManageRolesViewModel
    {
        private readonly UserManager<ApplicationUser> _userManager;

        public ManageRolesViewModel(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            Users = new SelectList(userManager.Users.ToList());
            Roles = new SelectList(roleManager.Roles.ToList());
        }

        public SelectList Users;
        public SelectList Roles;
        public string ManageRolesUser { get; set; }//contains the specific user the user selects
        public string ManageRolesRole { get; set; }//contains the specific role the user selects

        public List<ApplicationUser> GetUsersInRole(string role)
        {
            var users = _userManager.GetUsersInRoleAsync(role).Result.ToList();
            return users;
        }
    }

一些幫助,將不勝感激。

將您的視圖更改為如下所示,我使用了表單而不是表單方法和操作,這將確保表單內的所有輸入都被序列化為與它們名稱相同的參數

@model WebApplication3.Models.ManageRolesViewModel

<fieldset>
    @using (Html.BeginForm("AssignRole", "Account", FormMethod.Get))
    {
        <span>
            <label for="email">Users:</label>
            @Html.DropDownList("email", @Model.Users)
        </span>
        <span>
            <label for="role">Roles:</label>
            @Html.DropDownList("role", @Model.Roles)
        </span>

        <input class="btn btn-info" type="submit" name="assignRole"/>
    }

</fieldset>

由於“電子郵件”和“角色”與控制器簽名中的參數匹配,因此所選的ID將被傳遞(而不是文本值)

當然,這是基於您向下傳遞到視圖的selectList填充了“ dataValueField”和“ dataTextField”的前提。

我還(不一定需要)將您的AssignRoles方法賦予以下屬性:[HttpGet]

但這只是出於冗長的緣故。 我是堅持不懈的堅持者:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM