載入網頁或送出表單時,網頁顯示載入中(讀取中)畫面

 

有兩種作法一是利用ASP.NET MVC的AjaxOptions類別來做設定,二是使用jQuery.ajax()事件。

 

一、使用AjaxOptions類別

Controller為

using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string myName)
        {
            return View();
        }
    }
}

View為

@{
    ViewBag.Title = "Home Page";

    AjaxOptions AjaxOptions = new AjaxOptions()
    {
        HttpMethod = "post",
        Url = @Url.Action("Index"),
        OnBegin = "Start",
        OnComplete = "Stop"
    };
}

@using (Ajax.BeginForm(AjaxOptions))
{
    <input type="text" name="myName" id="myName" value="" />
    <input type="submit" value="送出" />
}

<img id="loading" src="http://i.imgur.com/3lMWGHa.gif" style="display:none;" />

@section scripts{
    <script>
        function Start() {
            $("#loading").css("display", "block");
        }

        function Stop() {
            $("#loading").css("display", "none");
        }
    </script>
}

 

二、使用jQuery.ajax()事件

Controller為

using System.Web.Mvc;

namespace 使用ajax.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(int id, string name)
        {
            return View();
        }
    }
}

View為

@{
    ViewBag.Title = "Home Page";
}

@section header{
    <style>
        img {
            border: 1px solid;
        }

        #loading {
            display: none;
            margin: 0 auto;
            width: 200px;
        }
    </style>
}

<div id="loading">
    <img src="http://i.imgur.com/3lMWGHa.gif" alt="">
</div>
<button id="send">send</button>

@section scripts{
    <script>
        $("#send").click(function myfunction() {
            $.ajax({
                url: "",
                method: "post",
                data: "id=1&name='aaa'",
                dataType: "html"
            });
        });

        $(document).ajaxStart(function () {
            $("#send").hide();
            $("#loading").show();
        });

        $(document).ajaxStop(function () {
            $("#send").show();
            $("#loading").hide();
        });
    </script>
}

 

參考資料:

AjaxOptions的使用

jQuery.ajax()