简体   繁体   English

将值从JavaScript传递到ASP.NET代码隐藏

[英]Passing values from JavaScript to ASP.NET code-behind

I have an ASP.NET Image control declared as: 我有一个ASP.NET Image控件声明为:

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

My JavaScript code is: 我的JavaScript代码是:

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: 我在我的Page_Load代码背后的图像控件中添加了“ onclick”属性,如下所示:

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: 这是我的图像控件的SortOrder.OnClick事件:

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

My problem is, the SortOrder.AlternateText is always "Ascending". 我的问题是,SortOrder.AlternateText始终为“升序”。 My code-behind doesn't seem to recognized the changes to the properties made by my javascript. 我的后台代码似乎无法识别我的JavaScript对属性所做的更改。

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. 服务器端控件上的属性不映射到客户端上的DOM属性。 Although setting the AlternateText on the server will output the requisite alt text, it's not a two way street. 尽管在服务器上设置AlternateText将输出必需的alt文本,但这不是双向的。

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. 一个隐藏的<asp:checkbox>可以通过javascript进行切换。

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. 使用javascript和元素更改的任何属性都保留在浏览器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM