javascript MVC 从局部视图调用函数不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30717191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC Calling a function from a partial view is not working
提问by kabichan
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..
这是我的第一个 MVC 应用程序,这一定很简单,但我一直在努力让它工作很多小时。
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):
我想在局部视图中显示一个表,并且能够从父视图中删除项目。简单的版本看起来像这样(实际应用不是关于水果):
What I have now
我现在拥有的
Partial View (_FruitList.cshtml)
部分视图 (_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)
父视图 (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)
控制器 (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)
我可以在父视图中查看带有水果数据的表格,但是单击Delete
按钮不会调用父视图中的 d 函数。(Javascript和JQuery的,应在局部视图中工作,因为我已经测试过alert
,并addClass
和他们工作得很好)
I'm very new to this so it's very likely that I'm missing some basic stuff but what am I missing?
我对此很陌生,所以很可能我错过了一些基本的东西,但我错过了什么?
采纳答案by DLeh
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
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>
回答by vandsh
I believe in the past I had used a HTML.ActionLinkfor the same goal of deleting something by Id:
我相信过去我曾使用过 HTML。ActionLink用于按 Id 删除某些内容的相同目标: