开发者

loading gif in mvc

I have a method in my controller like this

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

I have a html button in my view page and when I click on that I want a loading gif image to appear and then disappear after 2000ms. Below is my html

<input type="button" id="btnUpdate" value="Update" />
<img id="loading" src="/Images/ajax-loader.gif" alt="Updating ..." /> 
<div id="result"></div>
开发者_开发知识库

How can I call the controller method. I have seen Html.ActionLink but I want this on button click and not a hyperlink.

Please help


First change to UpdateResource method. Now it returns ActionResult:

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

We have to hide image when document is loaded so we change image tag to:

<img id="loading" src="../../Content/progress.gif" alt="Updating ..." style="display: none;" />

We have added style="display:none".

Then we are using 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>

When document is loaded, we are setting click action to your button. It shows progress and then uses ajax to get ActionResult. When ActionResult comes back, we are hiding progress and setting content of #result div with returned data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜