Reputation: 93
I have a .NET Core 2 MVC project, and I am very new to this. I have a Details View that contains data for a selected user. I am using a ViewModel to display that selected user's data and it is all working fine. What I am trying to ultimately do is allow for the cloning of one user's Identity Roles to the current selected user. So I have in my View a panel that contains a SelectList to where you can select some other user (I'm calling them the source user) to get their currently assigned Identity Roles. I then want to have a button that says "Clone" and on click remove all Roles for the current user and then add them to the Roles that the selected source user is assigned to.
Here is what I am using for my drop-down list:
View:
<select asp-for="EmployeeList" class="form-control"
asp-items="@Model.EmployeeList"
onchange="this.form.submit()">
<option disabled selected>-</option>
</select>
Controller:
var employeeList = _employeeRepository.GetEmployeeList().Select(e => new
{
Id = e.EmployeeId,
Value = e.PreferredFirstName != null ? e.LastName + ", " + e.PreferredFirstName : e.LastName + ", " + e.FirstName
});
ViewModel:
public SelectList EmployeeList { get; set; }
In my View I have a form for the post:
@using (Html.BeginForm("Details", "ApplicationUser", FormMethod.Post))
So I need to pass the selected id (string) of my source user drop-down list to the [HttpPost]
Details action in my controller. I also want to maintain the selected option in my drop-down list in the View. I also want to maintain all of the data that is being displayed in my ViewModel.
Your help is greatly appreciated.
Upvotes: 0
Views: 2264
Reputation: 477
As said before, your view is really not making sense. However we can fix that.
Viewmodel:
public List<SelectListItem> EmployeeList { get; set; }
View:
<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>
Controller:
[HttpPost("UpdateUser/{id}")]
public IActionResult UpdateUser([FromRoute] int id)
{
// Do things with id
}
Upvotes: 2