如何在OnSelectedChange上触发jquery函数?

时间:2011-07-18 15:22:39

标签: c# jquery asp.net

我正在我的页面上创建一个动态下拉列表。当从下拉列表中选择一个选项时,如何让它触发jquery函数?

Jquery的:

            <script type="text/javascript">
                $(document).ready(function () {
                   function insertIntoReporting(_storeID, _personID) {
                      $.ajax({
                        type: "POST",
                        url: "Default.aspx/InsertIntoReporting",
                        data: "{'storeID': _storeID, 'personID': _personID}",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        async: true,
                        cache: false,
                        success: function (msg) {
                        $('').text(msg.d);
                         }
                       });
                      return false;
                   }

                });


            </script>

C#代码背后

            DropDownList ddl = new DropDownList();
            ddl.ID = "DropdownlistID";
            ddl.Items.Add("----------");
            ddl.DataTextField = "StoreName";
            ddl.DataValueField = "StoreID";
            ddl.DataSource = ds;
            ddl.DataBind();
            e.Item.Cells[4].Controls.Add(ddl);


            [WebMethod]
            public static string InsertIntoReporting(int _storeID, string _personID)
            {
               // database calls go here
            }

2 个答案:

答案 0 :(得分:2)

将您的下拉列表存储在代码隐藏中的受保护字段中,然后:

$('<%=_ddl.ClientId%>').change(insertIntoReporting);

另一种选择是让您的insertIntoReporting功能更易于全局访问,然后执行以下操作:

e.Item.Cells[4].Controls.Add(new LiteralControl(
    string.Format(
        @"<script>$(function() {   
            $('{0}').change(insertIntoReporting);
        });</script>",
        ddl.ClientId)));

然而另一个选项(我个人更喜欢)是将一些类添加到您想要具有此行为的所有下拉列表中,并使您的javascript块包含一个选择所有类别的行:< / p>

$('.report-insert-dropdown').change(insertIntoReporting);

答案 1 :(得分:0)

您寻找jQuery's change事件。

看起来像这样:

$('#DropdownlistID').change(insertIntoReporting);
function insertIntoReporting(_storeID, _personID) {
    // $(this) refers to the element that fired the event
    //In this case $(this).val() should be the equivilant as _storeId
    //im not sure where _personId is coming from so I will assume its in an input with id of personId
    var _storeId = $(this).val();
    var _personID = $('#personId').val();
    $.ajax({
        type: "POST",
        url: "Default.aspx/InsertIntoReporting",
        data: "{'storeID': _storeID, 'personID': _personID}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
            $('').text(msg.d);
            }
    });
    return false;
}