Reputation: 57
I am working on a row select functionality for an ASP.NET Core project. Basically, a user selects a row in a table, that rows id is passed to javascript where it does some work, then sets an input field in the view to the value of that id, and binds that id to a SelectedId property in my ViewModel. That all seems to work properly. Once the row is selected though I have a couple of buttons that I want to be able to do something with that object (edit, delete, view). But when I try to pass the id from any of the buttons with asp-route-id or data-id, the id passed is always 0. I'm pretty sure that the SelectedId is not actually being changed in the ViewModel even though it is being updated in the input field, but I don't know how to fix that. This is how the code is written.
EmployeeListViewModel
public class EmployeeListViewModel
{
[BindProperty]
public int SelectedId { get; set; }
[BindProperty]
public string SelectedName { get; set; }
[BindProperty]
public IEnumerable<Employee>? EmployeeList { get; set; }
}
Edit and Delete buttons, and the input that receives the id and should also be passing it back to ViewModel's SelectedId property. I put these in a form tag, because I thought it might help, but it didn't. At least not as is.
Employee/ index.cshtml
@model Project.ViewModels.EmployeeListViewModel
...
//table
...
<form>
<div class="buttons">
<div class="w-100 btn-group" >
<input asp-for="SelectedId" class="form-control selectedId"/>
//input box shows correct selected Id
<button class="btn btn-primary mx-2" asp-controller="Employee" asp-action="Edit"
asp-route-id="@Model.SelectedId"> <i class="bi bi-pencil-square"></i>
Edit
</button>
<!--button call to delete modal (js.delete.js)-->
<a class="btn btn-danger delete" id="#delete" data-id="@Model.SelectedId"
data-controller="Employee" data-Action="DeletePOST"
data-body-message="Are you sure you want to delete this employee?">
<i class="bi bi-trash"></i>
Delete
</a>
//neither anchor or button or data-id or asp-route-id pass anything but id=0
</div>
</div>
</form>
EmployeeController.cs (Edit Action being called and passed id=0)
public IActionResult Edit(int? id)
{
//do something with id
}
Any help would be greatly appreciated. Thank you, everybody.
Update to this I decided to do a little test and initialize the SelectedId in my model to 25, and now when I select a row, I see the input change, but when I press a button, it returns 25. So the problem is 100% that the input or the asp-for taghelper are not updating the value of the SelectedId property in my ViewModel. So, possibly something about this line of code specifically.
<input asp-for="SelectedId" class="form-control selectedId"/>
Upvotes: 1
Views: 1701
Reputation: 71
change your code to :
<a class="btn btn-primary mx-2" asp-controller="Employee" asp-action="Edit"
asp-route-id="@Model.SelectedId"> <i class="bi bi-pencil-square"></i>
Edit
</a>
Upvotes: 1