我能给MVC Ajax回调一个参数吗?

Can I give the MVC Ajax callback a parameter?

本文关键字:一个 参数 MVC Ajax 回调      更新时间:2023-09-26
   @Ajax.ActionLink("Pujar",
                    "BidOnSmallAuction", 
                    "Auctions",
                    new { id = @item.UniqueIdentifierID },
                    new AjaxOptions { UpdateTargetId = "divright" + item.UniqueIdentifierID, InsertionMode = InsertionMode.Replace, OnSuccess = "Update" },
                    new { @class = "btn primary" })

例如,当我点击这个ActionLink时,javascript的"Update"方法将在回调后被调用。

由于这个ajax链接是在许多不同的拍卖,每个有它自己的计时器,我需要能够告诉更新方法哪个拍卖运行。

所以如果你能告诉我如何给Update方法传递一个参数,我就能算出剩下的了

感谢您的宝贵时间。


编辑:

根据两个答案的建议,我试着运行如下命令:

//Just for testing purposes.
function Update(uniqueDivId) {
    alert(uniqueDivId);    
} 
//And in the view's code:
@Ajax.ActionLink("Pujar",
                 "BidOnSmallAuction",
                 "Auctions",
                 new { id = @item.UniqueIdentifierID },
                 new AjaxOptions { UpdateTargetId = "divright" + item.UniqueIdentifierID,               
                                   InsertionMode = InsertionMode.Replace, 
                                   OnSuccess = "function() { Update(3); }" },
                 new { @class = "btn primary" })

警报消息没有被调用。什么好主意吗?

您可以尝试这样做:

@Ajax.ActionLink(
   "Pujar",
   "BidOnSmallAuction",
   "Auctions",
   new { id = @item.UniqueIdentifierID },
   new AjaxOptions { UpdateTargetId = "divright" + item.UniqueIdentifierID,
                     InsertionMode = InsertionMode.Replace,
                     OnSuccess = "function() { Update(someParam); }" },
   new { @class = "btn primary" }) 

这样OnSuccess本身调用一个没有参数的函数,但是这个函数反过来知道如何调用带参数的Update()。您应该能够使用字符串连接来设置所需的参数(类似于UpdateTargetId),例如:

...
new AjaxOptions { UpdateTargetId = "divright" + item.UniqueIdentifierID,
    InsertionMode = InsertionMode.Replace,
    OnSuccess = "function() { Update(" + item.UniqueIdentifierID + "); }" },
...
更新:

哦,对不起,看起来可能-也许-也许它只是期待一个函数的名字作为一个字符串,我以为它期待一个函数的引用。

你可以动态地在页面上包含其他脚本在同一时间作为你现有的代码?如果是这样,将上面的内容改为OnSuccess="UpdateProxy",然后动态输出以下内容:

<script>
function UpdateProxy() {
   Update(/* insert your item.UniqueIdentifierID or other params here */);
}
</script>

如果页面上同时有多个ajax链接,则需要UpdateProxy1(), UpdateProxy2()

你可以试试吗

OnSuccess = "function() { Update('"some param'"); }"