在mvc中加载gif

use*_*272 2 asp.net-mvc

我的控制器中有一个这样的方法

public string UpdateResource()
{
    Thread.Sleep(2000);
    return string.Format("Current time is {0}", DateTime.Now.ToShortTimeString());
}
Run Code Online (Sandbox Code Playgroud)

我的视图页面中有一个html按钮,当我点击它时,我想要一个加载的gif图像出现,然后在2000ms后消失.下面是我的HTML

<input type="button" id="btnUpdate" value="Update" />
<img id="loading" src="/Images/ajax-loader.gif" alt="Updating ..." /> 
<div id="result"></div>
Run Code Online (Sandbox Code Playgroud)

如何调用控制器方法.我已经看到了,Html.ActionLink但我希望在按钮点击而不是超链接.

请帮忙

Luk*_*Led 5

首先改为UpdateResource方法.现在它返回ActionResult:

public ActionResult UpdateResource()
{
    Thread.Sleep(5000);
    return Content(string.Format("Current time is {0}", DateTime.Now.ToShortTimeString()));
}
Run Code Online (Sandbox Code Playgroud)

我们必须在加载文档时隐藏图像,因此我们将图像标记更改为:

<img id="loading" src="../../Content/progress.gif" alt="Updating ..." style="display: none;" />
Run Code Online (Sandbox Code Playgroud)

我们补充说style="display:none".

然后我们使用jQuery:

<script type="text/javascript">
    $(document).ready(
        function() {
            $('#btnUpdate').click(
                function() {
                    $('#loading').show();
                    $.get('<%= Url.Action("UpdateResource") %>', {},
                        function(data) {
                            $('#result').html(data);
                            $('#loading').hide();
                        });
                }
            );
        }
    );
</script>
Run Code Online (Sandbox Code Playgroud)

加载文档后,我们将点击操作设置为您的按钮.它显示进度,然后使用ajax获取ActionResult.当ActionResult返回时,我们隐藏进度并使用返回的数据设置#result div的内容.