Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ASP.NET Button attributes client side and read attribute value server side

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

Example:

Asp file

<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 file

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"]; 
}

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?

like image 216
Ceparu Stefan Avatar asked Aug 26 '14 13:08

Ceparu Stefan


1 Answers

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

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.

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.

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;
} 

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

like image 87
Kelsey Avatar answered Nov 02 '22 14:11

Kelsey