简体   繁体   English

如何在没有Ajax Toolkit的情况下完全加载gridview之前显示加载图像?

[英]How to display a loading image until a gridview is fully loaded without Ajax Toolkit?

QUESTION

Can anyone suggest how a loading image can be displayed until a gridview is fully loaded? 任何人都可以建议如何在网格视图完全加载之前显示加载图像?

This gridview is to be rendered on page load. 此网格视图将在页面加载时呈现。 There must be a simple solution to detect when gridview is loading/loaded so a simple toggle between load image and gridview visibility can be achieved. 必须有一个简单的解决方案来检测何时加载/加载gridview,以便可以实现加载图像和gridview可见性之间的简单切换。

Please do not suggest using any of the Ajax toolkit methods unless the desired code can be isolated and used standalone. 除非可以隔离并单独使用所需的代码,否则请不要建议使用任何Ajax工具包方法 I have found the toolkit to be easy on implementation but bloated and slow on performance. 我发现该工具包易于实现,但性能臃肿且速度慢。 I do not wish to include any scripts, files or code in my release package that is not going to be used. 我不希望在我的发布包中包含任何不会使用的脚本,文件或代码。

ASP.NET ASP.NET

      <img src="~/Loading.gif"></img>

      <asp:GridView ID="gv" runat="Server" AutoGenerateColumns="False" EnableModelValidation="False">
        'content...
      </asp:GridView>

VB VB

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'connection info

    If Not IsPostBack Then
      Me.Bindgv()
    End If
  End Sub


  Private Sub Bindgv()
    'Load gridview
  End Sub

POSSIBILITIES 可能性

I am open to any suggestions however I was attemting to implement a solution using jquery page methods but need assistance to follow through. 我对任何建议持开放态度,但我正在努力使用jquery页面方法实现解决方案,但需要帮助才能完成。

JAVASCRIPT JAVASCRIPT

$(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/UpdateGV",
    data: "{}",
    contentType: "application/json",
    dataType: "json",
    success: function() {
      // Run return method.
    }
  });
});

VB.NET VB.NET

Imports System.Web.Services

Public Partial Class _Default
    Inherits System.Web.UI.Page

    <WebMethod(EnableSession := False)> _
    Public Shared Function UpdateGV() As String
         Return 
         Me.Bindgv()
    End Function
End Class

You can achieve this using jquery, there is a jquery block UI project on github and you could just use that one to block the grid view without using ajax. 你可以使用jquery实现这一点,在github上有一个jquery块UI项目,你可以使用那个来阻止网格视图而不使用ajax。

here is the code you will need to do this, and it' tested and works fine like below: 这里是您需要执行此操作的代码,并且它经过测试并且工作正常,如下所示:

Step 1 add these two lines in your page head 第1步在页面头部添加这两行

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script src="http://malsup.github.io/jquery.blockUI.js"></script> 

Step 2 an extension jquery after the codes above: 步骤2在上面的代码之后的扩展jquery:

 <script type="text/javascript"> $(document).ready(function () { $('#Button1').click(function () { $('.blockMe').block({ message: 'Please wait...<br /><img src="Images/loadingBar.gif" />', css: { padding: '10px' } }); }); }); </script> 

Step 3 in my case I bind my grid view using a button , but you could always use any other controls as well: 步骤3在我来说,我使用一个按钮绑定我的网格视图,但你总是可以使用任何其他控件,以及:

 <asp:Button ID="Button1" runat="server" Text="Bind Grid View" ClientIDMode="Static" OnClick="Button1_Click" /> <div class="blockMe"> <asp:GridView ID="GridView1" runat="server" Width="100%"> </asp:GridView> </div> 

Step 4 bind the grid view on button clicked 第4步单击按钮上的网格视图绑定

  protected void Button1_Click(object sender, EventArgs e) { DataTable tblCourse = myAccount.GetEnroledCourse("arpl4113"); //Bind courses GridView1.DataSource = tblCourse; GridView1.DataBind(); } 

and that's it, NO AJAX Toolkit (only jQuery) so the result will be look like this: 就是这样, 没有AJAX工具包 (只有jQuery)所以结果将如下所示:

在此输入图像描述


A trick to do the above solution at the page load 在页面加载时执行上述解决方案的技巧

First of all this is NOT a function on Page_Load event on server side but on the client side ;-) 首先,这不是服务器端的Page_Load事件,而是客户端的函数;-)

So to achieve this you need to have a hidden control to keep a value on page view-state and also make the same button hidden to trigger it on page load. 因此,为了实现这一点,您需要有一个隐藏控件来保持页面视图状态的值,并且还隐藏相同的按钮以在页面加载时触发它。 and a little changes on the extension jQuery above. 以及上面的扩展jQuery的一些变化。 Done! 完成!

Step 1. Add the css below to your page header: 步骤1.将以下css添加到页眉:

 <style> .hidden { display: none; } </style>

Step 2. Add a hidden field plus make your button hidden like this: 第2步。添加一个隐藏字段,并使您的按钮隐藏如下:

    <asp:HiddenField ID="hidTrigger" runat="server" ClientIDMode="Static" Value="" />
    <asp:Button ID="btnHidden" runat="server" ClientIDMode="Static" 
                OnClick="btnHidden_Click" CssClass="hidden" />
    <div class="blockMe">
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    </div>

Step 3. Make this changes on your extension script like below: 第3步。在扩展脚本上进行此更改,如下所示:

  <script type="text/javascript">
    $(document).ready(function () {

        //check whether the gridview has loaded
        if ($("#hidTrigger").val() != "fired") {

            //set the hidden field as fired to prevent multiple loading
            $("#hidTrigger").val("fired");

            //block the gridview area
            $('.blockMe').block({
                message: 'Please wait...<br /><img src="Images/loadingBar.gif" />',
                css: { padding: '10px' }
            });

            //fire the hidden button trigger
            $('#btnHidden').click();
        }
    });
</script>

That's it! 而已! and your button click on the code behind remains the same as before, in this example I only change the name of the button. 并且您点击后面的代码的按钮保持与以前相同,在此示例中,我只更改按钮的名称。 no code on Page_Load event though. 虽然没有关于Page_Load事件的代码。

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnHidden_Click(object sender, EventArgs e)
    {
        DataTable tblCourse = myAccount.GetEnroledCourse("arpl4113");

        //Bind courses
        GridView1.DataSource = tblCourse;
        GridView1.DataBind();
    }

I hope it helps you. 我希望它对你有所帮助。

As you are not willing to use the ASP.NET Update panel which is designed to handle the kind of requirement you have. 因为您不愿意使用旨在处理您所需要的ASP.NET Update面板。 Using jquery AJAX and using the web method to update the Grid will not work as you expect because you need to update the viewstate and other information. 使用jquery AJAX并使用Web方法更新网格将无法正常工作,因为您需要更新视图状态和其他信息。 One of the solution that you can apply is showing the modal dialog box till your page is completed loaded its html which includes your Grid data. 您可以应用的解决方案之一是显示模式对话框,直到您的页面完成加载其包含您的网格数据的html。

              <script type = "javascript/text">
              $(document).ready(function() { // show modal dialog });
              $(window).load(function() {// hide the dialog box});
              </script> 

I would implement this by using a web api controller that returns the appropriate data and then simply try to load the data on document.ready with jquery. 我将通过使用web api控制器来实现这一点,该控制器返回适当的数据,然后尝试使用jquery在document.ready上加载数据。 Something along the lines of this (Will be posting the answer in c# but it should be simple enough to translate): 有点像这样的东西(将在c#中发布答案,但它应该足够简单来翻译):

 public class TableDataController : ApiController
  {
     public IEnumerable<SimplePocoForOneTableRow> Get()
     {
        var tableData = GetTableDataFromSomewhere();

        return tableData;
     }
  }

To learn more about how to setup a WebApiController in a web forms project, please refer to this article . 要了解有关如何在Web表单项目中设置WebApiController的更多信息,请参阅此文章

I would implement the HTML something like this: 我会实现这样的HTML:

<table class="tableToLoadStuffInto">
   <tr>
       <td><img src="yourCoolSpinningAjaxLoader.gif" /></td>
   <tr>
</table>

And the jquery to load the data and present it in the table would look something like this: 加载数据并将其呈现在表中的jquery看起来像这样:

<script type="text/javascript">
$(document).ready(function () {
    jQuery.ajax({
            url: '/api/TableData',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
            if(!result) {
                //Show some error message, we didn't get any data
            }                    

            var tableData = JSON.parse(result);
            var tableHtml = '';
            for(var i = 0; i<tableData.length; i++){
                    var tableRow = tableData[i];
                    tableHtml = '<tr><td>' + 
                    tableRow.AwesomeTablePropertyOnYourObject +
                    '</td></'tr>'
               }    
             var table = $('.tableToLoadStuffInto');
             //Could do some fancy fading and stuff here
             table.find('tr').remove();
             table.append(tableHtml);
            }
        });
});
</script>

To tidy the string concatenation of the jQuery up a bit you could use a template like handlebars , but it's not strictly necessary. 为了整理jQuery的字符串连接,你可以使用像把手一样的模板,但这并不是绝对必要的。

You should load grid in another page and call that page in a div on parent page and display required loading image while loading div as per below code: 您应该在另一个页面中加载网格并在父页面上的div中调用该页面,并在加载div时显示所需的加载图像,如下面的代码所示:

  $(document).ready(function()
   {
 $("#loader").show();
 $.ajax({
    type: "GET",
    url: "LoadGrid.aspx",
    data: "{}",
    contentType: "application/json",
    dataType: "json",   
    success: function(data) {
        $("#loader").hide();
       $(#dvgrid).html(data);
    },
    // it's good to have an error fallback
    error: function(jqhxr, stat, err) {
       $("#loader").hide();
 $(#dvgrid).html('');
       $("#error").show();
    }
  });
});

In LoadGrid.aspx you should load grid by normal C# code. 在LoadGrid.aspx中,您应该使用普通的C#代码加载网格。 and simply your parent page will call the LoadGrid.aspx and rendered html will display in parent div with loading image... 只是你的父页面将调用LoadGrid.aspx并呈现html将显示在父div与加载图像...

From your code : 从您的代码:

$(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/UpdateGV",
    data: "{}",
    contentType: "application/json",
    dataType: "json",
    success: function() {
      // Run return method.
    },
    // add these lines
    beforeSend:function {
       //this will show your image loader
       $("$Loader").css("display","block");
    },
    complete:function {
       //this will hide your image loader provided that you give an id named Loader to your image
       $("$Loader").css("display","none");
    }
  });
});

Use beforeSend in conjunction with success and error like so: 使用beforeSendsuccesserror一起使用如下:

$(function() {
  $.ajax({
    type: "POST",
    url: "Default.aspx/UpdateGV",
    data: "{}",
    contentType: "application/json",
    dataType: "json",
    beforeSend: function() {
        $("#loader").show();
    },
    success: function() {
        $("#loader").hide();
        // Run return method.
    },
    // it's good to have an error fallback
    error: function(jqhxr, stat, err) {
       $("#loader").hide();
       $("#error").show();
    }
  });
});

(provided you have <img id="loader" src="..." /> and <img id="error" src="..." /> ) (假设你有<img id="loader" src="..." /><img id="error" src="..." />

complete fires after success and error so using both success and error instead of complete and error assures no overlap. successerrorcomplete火灾,因此使用successerror而不是completeerror确保没有重叠。

Hope this was what you were looking for! 希望这是你想要的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM