I want to be able to delete multiple database rows using a single ActionResult. However, due to the nature of the ActionResult, the code that is reached first will execute regardless and will throw an error. Would there be any way around this? - The reason i want to use one ActionResult is because i am passing an id value as one of its parameters. This id value is sent to the ActionResult from a view using an onclick event (therefore i cannot specify multiple ActionResults using a single onclick).
Below is the button (that when clicked, will send an id value to the ActionResult "DeleteUser"):
@foreach (var User in Model)
{
<tr>
<td>@User.UserID</td>
<td>@User.Username</td>
<td>@User.Email</td>
<td>@User.Password</td>
<td>@User.UserType</td>
<td><i class="fas fa-pen-square fa-lg"></i></td>
<td><i class="fas fa-minus-square fa-lg" onclick="location.href = '@Url.Action("DeleteUser","Admin", new { id = User.UserID })'"></i></td>
</tr>
}
The ActionResult "DeleteUser" (to which the id value is sent) can be seen below:
public ActionResult DeleteUser(int id)
{
//DONATOR DELETE --------
int currentUserDonator = db.tblDonator.Where(aa => aa.user_id == id).Select(a => a.donator_id).FirstOrDefault();
//Remove specific donator users payment details from donator payment details table in database
var userDonatorPayment = db.tblDonator_Payment_Details.Where(bb => bb.donator_id == currentUserDonator).First();
db.tblDonator_Payment_Details.Remove(userDonatorPayment);
//Remove specific user from the user table in database (DRY - May be re-used)
var User = db.tblUser.Where(ii => ii.user_id == id).First();
db.tblUser.Remove(User);
//Remove specific donator user from the donator table in database
var UserDonator = db.tblDonator.Where(aa => aa.user_id == id).First();
db.tblDonator.Remove(UserDonator);
db.SaveChanges();
//NPO DELETE --------
int currentUserNPO = db.tblNpo.Where(dd => dd.user_id == id).Select(d => d.npo_id).FirstOrDefault();
//Remove specific npo users banking details from npo bank table in database
var userNPOBanking = db.tblNpo_Bank.Where(qq => qq.npo_id == currentUserNPO).First();
db.tblNpo_Bank.Remove(userNPOBanking);
//Remove specific npo user from the npo table in database
var UserNPO = db.tblNpo.Where(mm => mm.user_id == id).First();
db.tblNpo.Remove(UserNPO);
db.SaveChanges();
return RedirectToAction("User_table");
}
As one can see above, the ActionResult has two "Sections" - one to delete a Donator user and another to delete an NPO user. However, in the case that i want to delete an NPO user, the code in the Donator "section" will execute, and will throw an error when reaching the second line:
var userDonatorPayment = db.tblDonator_Payment_Details.Where(bb => bb.donator_id == currentUserDonator).First();
The error states "System.InvalidOperationException: 'Sequence contains no elements'". Simply; i am asking as to whether there is any workaround to this problem or not? Thank you.