开发者

Get DataTable values from code behind to client side using javascript

开发者 https://www.devze.com 2023-01-29 23:34 出处:网络
I need help on getting a particular datatable values from the server to the client using javascript.

I need help on getting a particular datatable values from the server to the client using javascript.

开发者_开发知识库

Ex. In my class which is Countries.aspx.cs I have this somewhere on my code say on the page load.

DataTable dtbCountries = Repository.GetAllCountries;

my dtbCountries now contains this record

ID  Country
1   HongKong
2   Japan
3   Korea

In my webform I want to get the values of my dtbCountries using javascript

<script type="text/javascript">
   // my code here to get the dtbCountries values
</script>

What should I do? Or what's the best thing to do to expose my dtbCountries in the client.

Thanks in advance!


You have some options for this. First of all, I assume that what you need is the actual data and not any functionality given by the DataTable object, so you better create an entity (could be a struct) to store the table's data —it must be marked with Serializable attribute.

One of your options is to encapsulate retrieving it in a Page Method. These methods are exposed to JavaScript transparently (i.e., they have the same syntax as in the code behind). These methods need to be static, and be marked with the PageMethod attribute.

Another option would be to "write" the content of your table in the HTML in JSON format (a notation to represent objects in JavaScript).

Edit 2: The way to serialize something into JSON is by using the class System.Web.Script.Serialization.JavaScriptSerializer, creating an instance and calling .Serialize(<your-serializable-object>).

Edit: Added the following (working) example...

ASPX page:

<script type="text/javascript">// <![CDATA[
    function doTest( ) {
        try {
            PageMethods.test(theForm.qty.value, function( result ) {
                var  str = '';
                for ( var  key in result ) {
                    str += '\t{ '+ key +': '+ result[ key ] +' }\n';
                }
                alert('Page Method returned the following result:\n'+ (str || "{ }"));
            }, function( ex ) {
                alert('Page Method returned the following "'+ ex.get_exceptionType() +'" exception:\n'+ ex.get_message());
            });
        } catch( err ) {
            alert('Failed to execute Page Method:\n'+ err);
        }
    } // void doTest()
// ]]>
</script>
···
<form runat="server" id="form">
  <asp:scriptmanager runat="server" enablepagemethods="true" />

  <fieldset id="forma">
    <legend>WebMethod Test</legend>
    <label for="qty">
      Number of elements (>= 0):
      <input type="text" name="qty" id="qty" value="5" />
    </label>
    <input type="button" value="Push the button!" onclick="doTest(this)" />
  </fieldset>

</form>

And, on your code behind:

using System;
using System.Collections.Generic;
using System.Web.Services;

namespace Tests {

    public partial class Test : System.Web.UI.Page {

        [WebMethod]
        static public IDictionary<string,string> test( int length ) {
            if ( 0 > length ) {
                throw  new ArgumentException( "Length cannot be less than zero", "length" );
            }
            var  result = new Dictionary<string,string>( length );
            for ( int  i = 0;  i < length;  i ++ ) {
                result.Add(i.ToString(), Char.ConvertFromUtf32(65 + i) +"|"+ Char.ConvertFromUtf32(97 + i));
            }
            return  result;
        } // IDictionary<string,string> test( int )

    }

}
0

精彩评论

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