LoginSignup
3
4

More than 3 years have passed since last update.

ASP.NET MVC : jQuery.ajaxを使った非同期処理

Last updated at Posted at 2020-05-03

ASP.NET MVCで、jQuery.ajaxを使った非同期処理の実装方法を説明する。
ajaxを使うことで、ページ上の情報をページ遷移せずに更新できる。

簡単なサンプルを通して、GETやPOSTでの非同期処理の実装方法を確認する。

サンプル
テキストボックスに文字列を入力しボタンをクリックすると、サーバで処理が実行され、入力した文字列がそのまま返される。
返された文字列は、テキストボックスの下に表示される。

mvc.png

1. GET

$.get()を使って非同期処理を実現する。

クライアント

Index.cshtml
<script>
    $(function () {
        $('#getButton').click(function () {
            $.get('@Url.Action("Get", "Home")',
                { text: $('#textbox').val() },
                function (data) {
                    console.log(JSON.stringify(data));
                    $('#text').text(data['returnText']);
                }
            );
        });
    });
</script>

補足
※リクエストの送信先URLは、シングルクオーテーション「'」で囲むこと。
※「ReferenceError: $ is not defined」のエラーが出る場合、「jquery.min.js」が読み込めていない。
_Layout.cshtmlのbodyタグにある以下の行を、headタグ内に移動する。

<script src="~/lib/jquery/dist/jquery.min.js"></script>

サーバ

HomeController.cs
public IActionResult Get(string text)
{
    System.Diagnostics.Debug.WriteLine(text);

    System.Threading.Thread.Sleep(5000);

    return Json(new { returnText = text });
}

2. POST

$.post()を使って非同期処理を実現する。

GETと異なるのは、以下の2点。
* $.get()ではなく、$.post()を使う。
* リクエストの送信先は、HomeController.Get()ではなく、HomeController.Post()である。メソッドの上には、[HttpPost]を付けること。

クライアント

Index.cshtml
<script>
    $(function () {
        $('#postButton').click(function () {
            $.post('@Url.Action("Post", "Home")',
                { text: $('#textbox').val() },
                function (data) {
                    console.log(JSON.stringify(data));
                    $('#text').text(data['returnText']);
                }
            );
        });
    });
</script>

サーバ

HomeController.cs
[HttpPost]
public IActionResult Post(string text)
{
    System.Diagnostics.Debug.WriteLine(text);

    System.Threading.Thread.Sleep(5000);

    return Json(new { returnText = text });
}
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4