This is my first MVC application, and this must be something simple but I've been trying to make this work for so many hours now..
I want to display a table in a partial view and be able to delete items from the parent view. The simple version looks something like this (the actual application is not about fruits):
<div id="listOfFruits">
<table class="table">
<tr>
<th class="active">Description</th>
<th class="active">Amount</th>
</tr>
@foreach(var item in Model)
{
<tr>
<td>@item.Description</td>
<td>@item.Amount</td>
<td><button class=".." onclick="d(@item.FruitID)">Delete</button></td>
</tr>
}
</table>
</div>
@section scripts
{
<script type="text/javascript">
$(document).ready(function (){
function d(id){
var url = "/Fruit/DeleteFruit/";
$.post(url, {id: id})
.done(function(response){
$("#listOfFruits").html(response);
});
}
});
</script>
}
@{Html.RenderPartial("_FruitList", Model.FruitList);}
[HttpPost]
public ActionResult DeleteFruit(int id)
{
//Delete the selected fruit
FruitViewMode item = new FruitViewMode();
return PartialView(item.FruitList);
}
I can view the table with the fruit data in the parent view, but clicking the Delete
button does not call the d function in the parent view.
(Javascript and JQuery should be working in the partial view because I've tested alert
and addClass
and they work fine)
I'm very new to this so it's very likely that I'm missing some basic stuff but what am I missing?
d()
isn't declared in the global page scope, so it isn't found. declare it in the root of the <script>
tag (i.e., not within a document.ready
) to have access to it from the onclick
<script type="text/javascript">
function d(id){
var url = "/Fruit/DeleteFruit/";
$.post(url, {id: id})
.done(function(response){
$("#listOfFruits").html(response);
});
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With