acermate433s
acermate433s

Reputation: 2554

Passing values from JavaScript to ASP.NET code-behind

I have an ASP.NET Image control declared as:

<asp:Image runat="server" ID="SortOrder"
AlternateText="Ascending"
ImageUrl="~/images/sort_ascending.gif"
CssClass="Ascending"
EnableViewState="true"
 /> 

My JavaScript code is:

function ReverseSort() {
    var img = window.event.srcElement;
    if(img.className == "Ascending") {
        img.className = "Descending";
        img.alt = "Descending";
        img.src = "<%= ResolveClientUrl("~/images/sort_descending.gif") %>";
    } else {
        img.className = "Ascending";  
        img.alt = "Ascending";
        img.src = "<%= ResolveClientUrl("~/images/sort_ascending.gif") %>";
    }
}

I have added an "onclick" attribute to the Image control in my Page_Load code-behind like so:

protected void Page_Load(object sender, EventArgs e) {
    if (IsPostBack)
        return;

    SortOrder.Attributes.Add("onclick", "ReverseSort()");
}

This is my SortOrder.OnClick event for my Image Control:

if (SortOrder.AlternateText == "Ascending") {
    /* Sort ascending */
} else {
    /* Sort descending */
}

My problem is, the SortOrder.AlternateText is always "Ascending". My code-behind doesn't seem to recognized the changes to the properties made by my javascript.

Upvotes: 0

Views: 1187

Answers (2)

pitx3
pitx3

Reputation: 124

The only thing that's posted back to the server is name-value pairs. Any attributes changed using javascript with the element remain on the browser.

Upvotes: 0

nickd
nickd

Reputation: 4021

I wouldn't expect that to work. The attributes on the server side control do not map to the DOM attributes on the client side. Although setting the AlternateText on the server will output the requisite alt text, it's not a two way street.

What you could do is use a hidden server side control to keep the state of the sort. A hidden <asp:checkbox> which you toggle via javascript will do it.

Upvotes: 1

Related Questions