Sunday, May 19, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  104] [ 5]  / answers: 1 / hits: 16375  / 9 Years ago, mon, june 8, 2015, 12:00:00

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..



What I want to do



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):



enter



What I have now



Partial View (_FruitList.cshtml)



<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>


Parent View (Home.cshtml)



@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);}


Controller (FruitController.cs)



[HttpPost]
public ActionResult DeleteFruit(int id)
{
//Delete the selected fruit
FruitViewMode item = new FruitViewMode();

return PartialView(item.FruitList);
}


My Question



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?


More From » c#

 Answers
24

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>

[#66281] Friday, June 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
serena

Total Points: 488
Total Questions: 125
Total Answers: 114

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;