Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Calling a function from a partial view is not working

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 image description here

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?

like image 952
kabichan Avatar asked Jun 08 '15 19:06

kabichan


1 Answers

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>
like image 133
DLeh Avatar answered Nov 11 '22 10:11

DLeh