开发者

Passing ID of element to a C# web service (using JSON) from jQuery

开发者 https://www.devze.com 2022-12-22 22:00 出处:网络
I have ancontaining a list of divs that jQuery turns into progress bars. On .ready, I build a list of all of these progress bars and for each one, call a webservice that gets a value indicating how fu

I have an containing a list of divs that jQuery turns into progress bars. On .ready, I build a list of all of these progress bars and for each one, call a webservice that gets a value indicating how full the progress bar should be. In order to do this, I need to pass the ID of the div to the web service.

Because the divs are inside a ListView, I manually set the id to be id="completionbar_<%# Eval("MilestoneID") %>"

However, when I pass this id into my web service, it comes up as "undefined" every time. When I view the source, it looks like it's set correctly.

Here's the jQuery that calls my web service:

<script type="text/javascript" language="javascript">
$(document).ready(function() {
    $(".MilestoneCompletion").progressbar({ value: 0 });
    $.each($(".MilestoneCompletion"), function(index, barDiv) {
        $.ajax({
            type: "POST",
            url: "ProjectTracking.aspx/GetText",
            开发者_JAVA技巧data: "{'id':'" + $(barDiv).id + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            success:
                function(msg) {
                    $(barDiv).progressbar("value", msg.d);
                }
        });
    });
});
</script>

Here's the web service stub that doesn't do anything right now:

[System.Web.Services.WebMethod]
public static int GetText(string id)
{
    return 75; // returns completion percent
}

Here's where I'm setting the id of the div in the ListView:

<ItemTemplate>
<li class="ui-widget-content" >
...
<!-- when this div loads, I want to call my webservice -->
<div id="completionbar_<%# Eval("MilestoneID") %>" class="MilestoneCompletion" style="height:30px;"></div>
...
</li></ItemTemplate>

I'm thinking maybe the script is executing before the DIV id is set by the ListView databind?

Can I fix this, or is my approach fundamentally flawed?


$(barDiv).attr('id')


Not sure if it relates to your problem but I believe it should be:

Update: you only need to pass in a function(index) and then use this within the function to reference the div:

$(".MilestoneCompletion").each(function(index) {
    ...
    $(this).progressbar("value", msg.d);
0

精彩评论

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

关注公众号