简体   繁体   中英

Passing Javascript value to C# Code Behind

I've coded myself into a bit of a corner, and the suggestions I've come across don't seem to be helping.

In summary: I have a modal that takes in a serialized variable from the page on load event, passed through a javascript function that builds from a template of div's on the aspx page. The trouble is there's an ASP:LinkButton in the template that calls an onclick event in C#. I need to be able to pass some of the information that I have access to in the modal to the onclick function in C#.

I've tried using hidden variables but I can't seem to get them to change in the Javascript on the onclick.

Here's the link and hidden field, all in a contenttemplate (I have two, asp and html, been trying both):

<asp:LinkButton ID="lnkbtnProceedChangeStatus" runat="server" OnClick="ProceedChangeStatus_Click" CommandArgument="">Yes, proceed</asp:LinkButton>
<asp:Hiddenfield ID="hiddenInputField" value="test2" runat="server"/>
<input type="hidden" name="hiddenInputFieldHTML" id="CurrentlySelectedBatchID" value="test1" runat="server"/>

I try to use this to change the hidden variable,

document.getElementById('<%= hiddenInputField.ClientID %>').value = "test123";

then

string s = hiddenInputField.Value;
string t = hiddenInputFieldHTML.Value;

to try and pull it out in the codebehind, but they never change from their default values.

As @Brian Mains states, your approach is correct and should work.

I had a similar problem when using jQuery UI which turned out to be down to the way that the forms are manipulated in the DOM. If your dialog is a jQuery UI one the solution could be as simple as this:

$('#some-dialog').dialog({
    closeOnEscape: true,
    open: function(event, ui) {
        $(this).parent().appendTo("form"); //this line sorted everything!
    }
}); 

<asp:HiddenField> will always work fine, and the approach you have indicated will change it. The issue could be where you are calling it, either never getting called or the page is posting back while that's being set, and thus it never gets called because the page posted back too quickly...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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