简体   繁体   中英

Call ASP.Net Page Method using jQuery

Here i am pasting my code.

<script type="text/javascript">
        $(function() {
            var items = [{text: 'Onion', value: '1'},
                         {text: 'Ketchup', value: '2'},
                         {text: 'Mayonnaise', value: '3'},
                         {text: 'Pickles', value: '4'},
                         {text: 'Tomato', value: '5'},
                         {text: 'Patatoes', value: '6'},
                         {text: 'Sausage', value: '7'},
                         {text: 'Lettuce', value: '8'},
                         {text: 'Pepper', value: '9'}
                        ];

            $('#myCheckList').checkList({
                listItems: items,
                onChange: selChange
            });

            function selChange(){
                var selection = $('#myCheckList').checkList('getSelection');

                $('#selectedItems').text(JSON.stringify(selection));
            }


        });
    </script>

I want in var items= ,it will take a method ie getItems() and that method is written in ItemDAL.cs(DAL layer) and it is getting all the items list from database.How to do this? Can anyone suggest me?

Create ac# representation of your object:

public class SelectItem
{
    public string Value { get; set; }
    public string Text { get; set; }
}

Then a page behind web method:

    [WebMethod]
    public static List<SelectItem> GetItems()
    {
        var items = new List<SelectItem>();
        // look up db items and populate from your Dal          
        return items;
    }

Then your js

<script type="text/javascript">
        $(function() {
                var items;

                $.ajax({
                    type: "POST",
                    url: "Default.aspx/GetItems",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {

                        items = msg.d;

                    }
                });

            $('#myCheckList').checkList({
                listItems: items,
                onChange: selChange
            });

            function selChange(){
                var selection = $('#myCheckList').checkList('getSelection');

                $('#selectedItems').text(JSON.stringify(selection));
            }


        });
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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