[jQuery]使用jQuery ajax post 呼叫 .Net MVC Controller

說明如何透過jQuery的ajax post來呼叫後端Controller

例如我們想達成以下功能

1. 輸入姓名

2. 按下按鈕

3. ajax post 呼叫後端Controller傳回資料

4. 前端頁面接收資料後顯示

 

Controller

using System.Web.Mvc;

namespace MySample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Sample()
        {
            return View();
        }

        [HttpPost]
        public string Sample(string myName)
        {
            return "您好~ " + myName;
        }
    }
}

 

View

@{
    ViewBag.Title = "Hello World!";
}
<h2>@ViewBag.Title</h2>
<head>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
        $(document).ready(function () {

            (function ($) {
                $.fn.toggleDisabled = function () {
                    return this.each(function () {
                        this.disabled = !this.disabled;
                    });
                };
            })(jQuery);

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

                //失效按鈕 避免連點
                $(":submit").toggleDisabled();

                var actionUrl = "Sample?myName=" + $('#myName').val();

                $.post(actionUrl, function (data) {
                    alert(data);
                    $(":submit").toggleDisabled();
                })
                .fail(function () {
                    alert("something wrong...");
                })
            });
        })
    </script>
</head>
<p>
    <br />
    <input type="text" class="form-control" id="myName" value="@ViewBag.MyName" placeholder="請輸入您的大名" autofocus="autofocus">
    <br />
    <button type="submit" id="submit" class="btn btn-primary btn-sm btn-margin">送出</button>
</p>