I’m using asp.net C# MVC3 with razor templates and want to know the following:
I have a form, this form contains a button. If I click on the button the following code will be executed:
function OnGetSelectedFieldValues(result) {
for (var i = 0; i < result.length; i++) {
$("#id").val(result[i]); //This will replace the value of my hidden field with the selected id
$("#DeleteForm").submit();
}
}
According to my logic this should submit and delete each row that I have selected from my gridview.
It does select each record, this I have tested with an Javascript “alert()”.
But it only deletes the first record, why does this happen and how do I fix this?
Regards,
Marco
Edit:
This is my form(for easier understanding):
@using (Html.BeginForm("Delete", "Home", FormMethod.Post, new { id = "DeleteForm" }))
{
<input type="hidden" id="id" name="id" />
<input type="button" id="button" value="Verwijder geselecteerde" />
}
My Controller:
[HttpPost]
public ActionResult Delete(int id)
{
ErrorRepository repo = new ErrorRepository();
var test = repo.GetById(id);
repo.Delete(test);
return RedirectToAction("Index");
}
Because you are doing a direct POST on the form, it will only execute the first time through the loop as the form will already be posting by the time it gets to the next loop through.
This is not the proper way to handle multiple deletes but if you must do it this way you’ll need to create an AJAX post method so that multiple deletes can happen asynchronously.
The better way would be to pass the full list of ID’s to delete to the form POST and then delete them all at once on the server side. You should build a string of comma separated ID’s and send that to the POST method. Then in the method use
If you must do it through multiple posts, you’ll want something like: