MVC从局部视图调用函数不起作用

kab*_*han 5 javascript c# asp.net-mvc jquery asp.net-mvc-5

这是我的第一个MVC应用程序,它一定很简单,但是我已经尝试了好几个小时了。

我想做的事

我想在局部视图中显示表格,并能够从父视图中删除项目。简单版本看起来像这样(实际的应用程序与水果​​无关):

在此处输入图片说明

我现在有什么

局部视图(_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>
Run Code Online (Sandbox Code Playgroud)

父视图(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);}
Run Code Online (Sandbox Code Playgroud)

控制器(FruitController.cs)

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

    return PartialView(item.FruitList);
}
Run Code Online (Sandbox Code Playgroud)

我的问题

我可以在父视图中查看带有水果数据的表,但是单击Delete按钮不会在父视图中调用d函数。(由于我已经测试了Javascript和JQuery,所以它们应该在局部视图中工作alertaddClass并且它们可以正常工作)

我对此很陌生,因此很可能我缺少一些基本的东西,但是我缺少什么呢?

DLe*_*Leh 6

d()未在全局页面范围内声明,因此未找到。在<script>标记的根中声明它(即不在 a 内document.ready)以从onclick

<script type="text/javascript">
    function d(id){
        var url = "/Fruit/DeleteFruit/";
        $.post(url, {id: id})
        .done(function(response){
            $("#listOfFruits").html(response);
        });
    }
</script>
Run Code Online (Sandbox Code Playgroud)