MVC Razor Ajax 从按钮单击调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39301192/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 10:30:40  来源:igfitidea点击:

MVC Razor Ajax call from button click

ajaxasp.net-mvcrazor

提问by GPaw

I'm struggling to get a button click to invoke an Ajax function which then posts to a controller action. Cannot even get a simple message to work (nothing happens when button is clicked). Clearly, I'm missing something fundamental. What is it?

我正在努力获得一个按钮点击来调用一个 Ajax 函数,然后发布到一个控制器动作。甚至无法获得一条简单的消息(单击按钮时什么也没有发生)。显然,我错过了一些基本的东西。它是什么?

The Ajax script in my Razor form:

我的 Razor 形式的 Ajax 脚本:

<script type="text/javascript">
    $('#UseShipAddr').click(function () {
        $.ajax({
            url: "@(Url.Action("UseShippingAddress", "Checkout"))",
            type: "POST",
            data: { id: 50 },
            cache: false,
            async: true,
            success: function (data) {
                alert(data);
            }
        });
    });
</script>

The button that I want to use to invoke the Ajax function:

我想用来调用 Ajax 函数的按钮:

<input type="button" value="Use Shipping Address" id="UseShipAddr" />

The action in CheckoutController:

CheckoutController 中的操作:

// Ajax POST: /Checkout/UseShippingAddress/5
        [HttpPost]
        public ActionResult UseShippingAddress(int id)
        {            
            return Content("It worked!");
        }

回答by ghodasara keval

Please try this code.

请试试这个代码。

$(document).ready(function(){

    $('#UseShipAddr').click(function () {

        $.ajax({
            url: "Checkout/UseShippingAddress",
            type: "POST",
            data: { id: 50 },
            cache: false,
            async: true,
            success: function (data) {
            alert(data);
        }
    });
});