Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c# - Use Return Value of JSON in jQuery.Ajax Script Correctly

I have 2 DropDownList, like Master-Slave. This is my Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
            <asp:Label ID="MsLbl" runat="server" Text="Groups" />
                </td>
                <td>
            <asp:DropDownList ID="Masterddl" runat="server">
                    <asp:ListItem Text="G1" Value="G1" />
                    <asp:ListItem Text="G2" Value="G2" />
                    <asp:ListItem Text="G3" Value="G3" />
            </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
            <asp:Label ID="Svlbl" runat="server" Text="Members" />
            </td>
                <td>
            <asp:DropDownList ID="Slaveddl" runat="server" />
            </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

And this is my Script:

$(document).ready(function () {
$('select#Masterddl').change(function () {
    MasterChangeHandler($(this).val());
});

function MasterChangeHandler(Value) {
    $.ajax({
        type: 'Post',
        url: 'MasterSlaveHandler.ashx',
        dataType: "text",
        data: 'ItemSelected=' + Value,
        async: 'true',
        success: function (data) { SuccessHandler1(data); }

    });
}


function SuccessHandler1(data) {
    $('select#Slaveddl').empty();
    $.each(data, function (i, slaveValue) {
        $('select#Slaveddl').append(
    $('<option></option>').val(slaveValue.Value).html(slaveValue.Text)
    );
    });
}

And My Handler:

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


public class MasterSlaveDropDownListsHandler : IHttpHandler {
    public bool IsReusable {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context) {
        string valueSelected = context.Request["ItemSelected"];
        List<SlaveValues> slaveValues = new List<SlaveValues>();
        SlaveValues sv;

        sv = new SlaveValues();
        sv.Text = "SV1";
        sv.Value = valueSelected + "s1";
        slaveValues.Add(sv);

        sv = new SlaveValues();
        sv.Text = "SV2";
        sv.Value = valueSelected + "s2";
        slaveValues.Add(sv);


        string responseText =
    Newtonsoft.Json.JsonConvert.SerializeObject(slaveValues);
        context.Response.ContentType = "text/json";
        context.Response.Write(responseText);
    }
}

but there is nothing to append. Also I see the response in firebug windows as following(when I Select G2 from Master ddl):

[{"Value":"G2s1","Text":"SV1"},{"Value":"G2s2","Text":"SV2"}]

And for more specific view the following pic is the JSON tab in firebug windows when I select G3 in Master ddl:

JSON tab in firebug window

I change my success method of script with this new one for test:

function SuccessHandler2(data) {
    $('select#Slaveddl').empty();
    $.each(data, function (i, slaveValue) {
        $('select#Slaveddl').append(
    $('<option></option>').val('Member' + i).html('Member' + i)
    );
    });
}

when try this new script the binding to Slave ddl work correctly but with some additional items : the index show member0 to member30 and I don' know why.

I also try this one and append correctly:

function SuccessHandler3(data) {
var values = [{ "Value": "G2s1", "Text": "SV1" }, { "Value": "G2s2", "Text": "SV2"}];
        $('select#Slaveddl').empty();
        $.each(values, function (i, slaveValue) {
            $('select#Slaveddl').append(
$('<option></option>').val('Member' + slaveValue.Value).html('Member' +
 slaveValue.Text)
        );
        });
    }

So I think there is a problem with manipulate of return value (data).

Also I try this one and just the first alert appear, apparently the (data.d) is null or unknown object:

function SuccessHandler4(data) {
    var selection = $('select#Slaveddl');
    $(selection).children().remove();
    alert('in handler and remove children correctly');
    if (data.d) {
        alert('data.d is not null');
        $(data.d).each(function (index, item) {

$(selection).append('<option>').val(item.Value).html(item.Text);
            alert('after append in index: ' + index);
        });
    }
}

How can I use return value correctly and append to Slave ddl? Where is the problem?

Edit:

Find it with some changes in script and handler as following:

Script:

$(document).ready(function () {
$('select#Masterddl').change(function () {

    CallHandler();

});

function CallHandler() {
    $.ajax({
        url: "FinalRequest.ashx",
        contentType: "application/json; charset=utf-8",
        data: { 'ItemSelected': $('select#Masterddl').val(), 'ID':
  $('select#Masterddl').attr('id') },
        dataType: "json",
        responseType: "json",
        success: function (data) { SuccessHandler(data); },
        error: OnFail
    });
    return false;
}

function SuccessHandler(data) {
    $('select#Slaveddl').empty();
    $.each(data, function (i, slaveValue) {
        $('select#Slaveddl').append(
    $('<option></option>').val(slaveValue.Value).html(slaveValue.Text)
    );
    });
}

function OnFail(result) {
    alert('Request failed');

}

});

Handler:

public class FinalMasterSlaveHandler : IHttpHandler {


    public bool IsReusable {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context) {
        string valueSelected = context.Request["ItemSelected"];
        string IDSelected = context.Request["ID"];

        List<SlaveValues> slaveValues = new List<SlaveValues>();
        SlaveValues sv;

        sv = new SlaveValues();
        sv.Text = valueSelected + IDSelected + "T1";
        sv.Value = valueSelected + IDSelected + "V1";
        slaveValues.Add(sv);

        sv = new SlaveValues();
        sv.Text = valueSelected + IDSelected + "T2";
        sv.Value = valueSelected + IDSelected + "V2";
        slaveValues.Add(sv);

        JavaScriptSerializer javaScriptSerializer = new 
JavaScriptSerializer();
        string responseText = javaScriptSerializer.Serialize(slaveValues);

        context.Response.ContentType = "text/json";
        context.Response.Write(responseText);
    }



}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the sea that is your code, I found dataType: 'text' which should be dataType: 'json'.

Please see the jQuery.ajax(settings) documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...