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

4

9

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?

Maharanee answered 26/8, 2014 at 13:55 Comment(0)
L
4

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.

Lambart answered 26/8, 2014 at 14:40 Comment(4)
I've seen an example where you can edit the javascript:__postback() action and send the actIndex as an argument, but I haven't make it work, so I'll stick to your idea to use a hidden input field.Maharanee
@CeparuStefan Let me know if it doesn't work (I have tested it and it should though). Also, if this answer or any others have helped you, don't forget to upvote / set the accepted answer. And welcome to SO :)Lambart
Your method works. But I'm not sure if this is the best way to achieve what I was asking for, so it wouldn't be fair to mark your post as an answer. I was trying to give your post an upvote but it doesn't let me because I'm new to this site and I don't have enough points. Anyway I'm using this solution until I'll found a better one.Maharanee
@CeparuStefan Did you end up finding another solution?Lambart
E
0

only form elements can actually postback data. The server side will take the postback data and load it into the form element provided that the runat=server is set.

in markup or html:

<input type="hidden" runat="server" ID="txtHiddenDestControl" />

javascript:

document.getElementById('<%= txtHiddenDestControl.ClientID %>').value = '1';

code behind:

string postedVal = txtHiddenDestControl.Value.ToString();
Este answered 18/10, 2016 at 6:28 Comment(0)
R
0

You can define 1 o more buttons with the attribute, that use the same OnClick method ("ButtonSearchName_Click").

<asp:Button ID="ButtonSearchName" runat="server" Text="Search Name" 
data-sendto="filter"
OnClick="ButtonSearchName_Click"  />
                     
<asp:Button ID="ButtonSearchName2" runat="server" Text="Search Name" 
data-sendto="form"
OnClick="ButtonSearchName_Click"  />        

Then you can cast the "sender" in order to get the button that has been clicked and of course the attribute.

In the code below, there is also a HashSet to evaluate if the VALUE of the "attribute" is implemented.

Save the Attribute into a hidden field (or something) for further uses.

private readonly HashSet<string> listAttrValues = new HashSet<string>()
{
    "form", "filter"
};

/// <summary>
/// GET 
/// </summary>
protected void ButtonSearchName_Click(object sender, EventArgs e)
{

    // INIT - indica dove scrivere il fornitore selezionato (form/filter)
    hiddenFieldDatagridSendTo.Value = _getAttributeSendTo(sender);
}

/// <summary>
/// GET - attribute
/// </summary>
private string _getAttributeSendTo(object sender)
{
    // GET 
    string retObj = ((Button)sender).Attributes["data-sendto"];
    // CTRL
    if (!listAttrValues.Contains(retObj))
    {
        // ERR
        throw new Exception("Attribute not implemented: " + retObj);
    }
    // RET
    return retObj;
}


Reinold answered 15/3, 2023 at 8:57 Comment(0)
G
-2

NO need for Javascript below code will work for you

 protected void Page_Load(object sender, EventArgs e)
    {
        Button2.Attributes.Add("actIndex", "1");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string Value = Button2.Attributes["actIndex"].ToString();//1
        Button2.Attributes.Remove("actIndex");
        Button2.Attributes.Add("actIndex", "2");
         Value = Button2.Attributes["actIndex"].ToString();//2

    }
Grantgranta answered 26/8, 2014 at 14:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.