设置ASP.NET按钮属性的客户端和读取属性值的服务器端 [英] Setting ASP.NET Button attributes client side and read attribute value server side

查看:73
本文介绍了设置ASP.NET按钮属性的客户端和读取属性值的服务器端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以检索按钮自定义属性使用JavaScript的属性值已更改后?

How can I retrieve a Button custom attribute after the attribute value has been changed using javascript?

例如:

.asp文件

<asp:Button ID="Button1" runat="server" Text="Button1" />
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />

<script type="text/javascript">
var btn1 = '#<% Button1.ClientID %>';
var btn2 = '#<% Button2.ClientID %>';

$(btn1).click(function(e) {
    e.preventDefault();
    $(btn2).attr("actIndex", "2");
});

</script>

codeBehind文件

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        Button2.Attributes.Add("actIndex","1");
}

protected void Button2_Click(object sender, EventArgs e)
{
     Button btn = (Button)sender;

     // this should be 2 if button1 has been clicked
     string actIndex = btn.Attributes["actIndex"]; 
}

如果我点击 Button1的然后我点击将Button2 actIndex 值仍然是1,但如果我使用页面检查将Button2 actIndex 属性为2,不知何故属性值不传递给回传行动。

If I click Button1 then I click Button2 the actIndex value is still "1" but if I use page inspect the Button2 actIndex attribute is "2", somehow the attribute value is not passed to postBack action.

我怎样才能解开这个谜?

How can I solve this mystery?

推荐答案

我觉得你这个问题是因为属性不被调回有他们的信息重建的服务器端。

I think the problem you have is because the attributes are not being posted back to have their information rebuilt server side.

控件的状态是建立服务器端和存储在的ViewState 它提供了页面之前。然后,您修改使用JavaScript,因为vaule没有被回发到服务器,没有任何效果的价值。在回发时,服务器重建从已知的ViewState 里面有你最初分配这是值的默认值控制 1

The control's state is built server side and stored in the ViewState before it serves up the page. Then you modify the value using javascript which has no effect because that vaule is not being posted back to the server. On PostBack, the server rebuilds the control from the known ViewState which has the default value you originally assigned which is the value 1.

要解决这个问题,你需要的值存储在某些类型的控件(想了 HiddenField 控制),将得到回发到服务器,然后重建属性服务器端。

To get around this you need to store the value in some type of control (thinking a HiddenField control) that will get posted back to the server and then rebuild the attribute server side.

例如(半伪code):

eg (semi pseudo code):

// In your javascript write to a hidden control
$("#yourHiddenFieldControlName").val("2");

// Then in your server side c# code you look for this value on post back and if found,
// assign it to you attribute
if (!string.IsNullOrEmpty(yourHiddenFieldControlName.Value))
{
    Button2.Attributes["actIndex"] = yourHiddenFieldControlName.Value;
} 

您控制需要,如果你正在使用JavaScript修改它的客户端进行手工处理。

Your control needs to be handled manually if you are modifying it client side with javascript.

这篇关于设置ASP.NET按钮属性的客户端和读取属性值的服务器端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆