James James - 4 months ago 52
Ajax Question

C#- Loading icon when pressing submit

I am creating a MVC website, and one of the things I wanted was a spinning gif when pressing the submit button I have, until the new view loads. Below is my current code that unfortunately doesn't work and I don't know why.

<p>
@using (Ajax.BeginForm("Index", "Home", FormMethod.Get, new AjaxOptions ()
{
UpdateTargetId = "result",
LoadingElementId = "myLoadingElement"
}))
{
@Html.TextBox("search", null, new { style = "width:500px;" })<input type="submit" value="search" />
}
</p>

//some more code

<div id="myLoadingElement" style="display: none;">
<img src="~/photos/image"/>
</div>


Does anyone know what my problem may be? I am pretty new to MVC and this is my first time trying to use AJAX
Thanks

Answer
  1. LoadingElementId should be pointing directly to the .gif image
  2. Your image src attribute doesn't look right, it should be something like src="~/photos/image/loading.gif"
  3. Finally,for AJAX calls to work properly in MVC you need to add a refrence to three javascript libraries.Please note - the order matters:

    3.1)jquery-1.8.0.js

    3.2)jquery.validate.js

    3.3)jquery.unobtrusive-ajax.js

Complete example below.

Controller:

public class HomeController : Controller
{
    public string Index(string search)
    {
        Thread.Sleep(5000);
        return "Hello " + search;
    }
}

View:

<script src="~/scripts/jquery-1.8.0.js"></script>
<script src="~/scripts/jquery.validate.js"></script>
<script src="~/scripts/jquery.unobtrusive-ajax.js"></script>

@using (Ajax.BeginForm("Index", "Home", null, new AjaxOptions()
        {
            UpdateTargetId = "result",
            LoadingElementId = "myLoadingElement"
        },
            null))
{
    @Html.TextBox("search", null, new { style = "width:500px;" })
    <input type="submit" value="search" />
}

<img id="myLoadingElement" src="~/photos/image/loading.gif" style="display:none;width:70px;height:70px;" />
<div id="result">
</div>

EDIT:

Ajax.BeginForm is used when you want to call a controller action and display the result on the same page.If you want to call a controller action and redirect to a different view when you're done you should use the standard Html.BeginForm and to make the loading .gif appear use jQuery:

<script src="~/scripts/jquery-1.8.0.js"></script>
<script type="text/javascript">
    $(function () {
        $("#myform").submit(function (e) {
            $("#myLoadingElement").show();
        });
    });
</script>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "myform" }))
{
    @Html.TextBox("search", null, new { style = "width:500px;" })
    <input type="submit" value="search" />
}
<img id="myLoadingElement" src="~/photos/image/loading.gif" style="display:none;width:70px;height:70px;" />
Comments