代码之家  ›  专栏  ›  技术社区  ›  James

C#-按提交时加载图标

  •  1
  • James  · 技术社区  · 10 年前

    我正在创建一个MVC网站,我想要的其中一件事是在按下提交按钮时旋转gif,直到加载新视图。下面是我当前的代码,不幸的是它不能工作,我不知道为什么。

    <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>
    

    有人知道我的问题是什么吗?我对MVC很陌生,这是我第一次尝试使用AJAX 谢谢

    1 回复  |  直到 10 年前
        1
  •  0
  •   Denys Wessels    10 年前
    1. LoadingElementId 应该直接指向 .gif 形象
    2. 您的图像 src src="~/photos/image/loading.gif"
    3. 最后,为了让AJAX调用在MVC中正常工作,您需要添加对三个javascript库的引用。请注意- 命令很重要 :

      3.1)jquery-1.8.0.js

      3.2)jquery.validate.js

    完成下面的示例。

    控制器:

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

    视图:

    <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>
    

    编辑:

    Ajax.BeginForm 当您想调用控制器操作并在同一页面上显示结果时,使用。如果您想调用控制器操作,并在完成后重定向到其他视图,则应使用标准 Html.BeginForm 并使用jQuery显示加载的.gif:

    <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;" />