Ajax

This is a follow up to my previous article.

398px-ajax_logo_by_gengns-svg

Now I introduce a client event handler instead of the server postback, which is inconvenient since it causes a page reload. See the git repo diff below.

u9rlvo

nhhd7p

And here is the initial Javascript test, only to prove that the event is correctly fired.

var idSel = 1;
function test(sel) {
    idSel = sel.value;
    var selTxt = sel.options[sel.selectedIndex].innerHTML;
    $('#<%= TextBox1.ClientID %>').val(selTxt);
}

Next, I move to an Ajax implementation for the button click event. Again, we have to capture it on the client(this time it is a vanilla html, no asp:button):

<button type='button' onclick="btnClick()">Add to table</button>

to avoid page refresh.

There is a strange setting that must be removed in RouteConfig.cs under App_Code
Finally we call the Ajax

function btnClick() {
    $.ajax({
        type: "POST",
        url: "MyPage.aspx/AddRow",
        async: true,
        data: JSON.stringify({ selectedId: idSel }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (resp) {
            alert(JSON.stringify(resp));
        },
        error: function (e) {
            alert('Error: ' + JSON.stringify(e));
        }
    });
}

And we execute a WebMethod

private static async Task<Person[]> GetPeopleFromDB()
{
    await Task.Delay(2000).ConfigureAwait(false);
    return new Person[2]
        {
                new Person() { Id = "1", Name = "Johnny", Surname = "English" },
                new Person() { Id = "2", Name = "Eva", Surname = "Summer" }
        };
}

[WebMethod(EnableSession =true)]
public static async Task<Person[]> AddRow(int selectedId)
{
    var people = await GetPeopleFromDB().ConfigureAwait(false);
    var selected = GetPeopleFromDB().FirstOrDefault(p => p.Id == selectedId.ToString());
    if (selected != null)
        Persons.Add(new Person() { Name = selected.Name, Surname = selected.Surname, Id = (counter++).ToString() });
    return Persons.ToArray();
}

Notice that we can’t access the Web Controls from a WebMethod, so we have an abstract response in terms of business objects of the application model.
Now we have to complete the javascript on the client to populate the table: that’s a homework assignment for you!

Advertisements

2 thoughts on “Ajax

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s