I have a partial view:
@using confidenitial.DB.DataLayer;
<div id="page">
@{
List<Network> networks = (List<Network>)ViewData["Networks"];
<table>
<tr>
<td style="text-align: center">ID</td>
<td style="text-align: center">Name</td>
<td style="text-align: center" colspan="2">Modify</td>
</tr>
@foreach (Network n in networks)
{
<tr>
<td style="text-align: center">
@n.ID
</td>
<td style="text-align: center">
@n.Name
</td>
<td>
<button>Rename</button>
</td>
<td>
<button onclick="removeNetwork()">Delete</button>
</td>
</tr>
}
</table>
}
</div>
@section Scripts{
<script>
function removeNetwork() {
$.ajax({
url: "/Admin/removeNetwork",
type: "GET",
data: { id: id}
}).done(function (result) {
$('#page').html(result);
});
}
</script>
}
Controller:
[HttpPost]
public ActionResult removeNetwork(int id)
{
//query
return PartialView("_Whatever");
}
I want it to call the removeNetwork
method form the controller but for some reason it's not firing. I would say it's my fault but I wrote the exact same ajax when calling addNetwork
and that works fine.
@section Scripts{
<script>
function addNetwork() {
$.ajax({
url: "/Admin/addNetwork",
type: "GET",
data: { newNetwork: newNetwork.value }
}).done(function (result) {
$('#table').html(result);
$('#newNetwork').val("");
});
}
</script>
}
What is the big difference between the two? I can't figure it out.
Edit:
I found what the problem was: the function can't be in the partial view so I placed it in the main view. I discovered this after looking at the html the server spit out (the script section did not contain this script).
Your removeButton
method is reading value of a variable id
which is neither declared as global or not passed to the method. So change your method to accept that as a parameter.
<script>
function removeNetwork(id) {
$.ajax({
url: "/Admin/removeNetwork",
type: "GET",
data: { id: id }
}).done(function (result) {
$('#page').html(result);
});
}
</script>
and in your markup, pass that to your method.
<td>
<button onclick="removeNetwork(@n.ID)">Delete</button>
</td>
This should work.
You do a GET request in ajax (type: "GET") but your action is configured to be used as POST request ([HttpPost] attribute) you must change the attribute of your action by [HttpGet] or the ajax request by POST instead of GET