ASP.NET MVC从selectlist传递值

问题描述 投票:-1回答:1

我有一个.NET Core 2 MVC项目,我对此非常陌生。我有一个详细信息视图,其中包含所选用户的数据。我正在使用ViewModel来显示所选用户的数据,并且一切正常。我最终要做的是允许将一个用户的身份角色克隆到当前所选用户。所以我在我的View中有一个包含SelectList的面板,您可以在其中选择其他用户(我称之为源用户)来获取他们当前分配的身份角色。然后,我想要一个“Clone”按钮,然后单击删除当前用户的所有角色,然后将它们添加到所选源用户所分配到的角色。

以下是我在下拉列表中使用的内容:

视图:

<select asp-for="EmployeeList" class="form-control"
    asp-items="@Model.EmployeeList"                                 
    onchange="this.form.submit()">
    <option disabled selected>-</option>
</select>

控制器:

var employeeList = _employeeRepository.GetEmployeeList().Select(e => new
{
    Id = e.EmployeeId,
    Value = e.PreferredFirstName != null ? e.LastName + ", " + e.PreferredFirstName : e.LastName + ", " + e.FirstName                            
});

视图模型:

public SelectList EmployeeList { get; set; }

在我的视图中,我有一个帖子的表单:

@using (Html.BeginForm("Details", "ApplicationUser", FormMethod.Post))

所以我需要将我的源用户下拉列表的选定id(字符串)传递给我的控制器中的[HttpPost] Details操作。我还想在视图的下拉列表中维护所选选项。我还想维护我的ViewModel中显示的所有数据。

非常感谢您的帮助。

asp.net-mvc asp.net-core-mvc selectlist
1个回答
1
投票

如前所述,你的观点真的没有意义。但是我们可以解决这个问题

视图模型:

public List<SelectListItem> EmployeeList { get; set; }

视图:

<select id="employee-select" asp-for="EmployeeId" class="form-control" onchange="postEmployee()" asp-items="@Model.EmployeeList">
    <option disabled selected>-</option>
</select>

<script>
    function postEmployee() {
        var id = $('#employee-select').val();
        if (id !== '' && id != null) {
            var url = '../CONTROLLERNAME/UpdateUser/' + id;
            var settings = {
                "url": url,
                "method": 'POST'
            };
            $.ajax(settings);
        }
    }
</script>

控制器:

[HttpPost("UpdateUser/{id}")]
public IActionResult UpdateUser([FromRoute] int id)
{
    // Do things with id
}
© www.soinside.com 2019 - 2024. All rights reserved.