Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

How to Access Server-Side Values from jQuery

2.00/5 (2 votes)
1 Jul 2015CPOL2 min read 18.4K  
Use Hidden Fields to Access Code-Behind/Server-Side Vals from Your Client-side (jQuery) code

jQuery Queries C#, You Betcha

In my Sharepoint app, I needed to access some data that the server-side code knew about. Specifically, when the user selected a certain radio button, I needed to update the value in a text input element. In a nut's hell (similar to a nutshell, but a smidgen more painful*), here's how to do it:

0) Create a Hidden element to house the value in your server-side/code-behind (C#) code:

C#
HiddenField hfUserEmail = new HiddenField();
hfUserEmail.ID = "hfuseremail";
hfUserEmail.Value = userEmail;
this.Controls.Add(hfUserEmail);

Name the HiddenField anything you want (ray, jay, whatever) and give it any ID you want. Be sure, though, to assign its Value property the value you want to access from the client-side.

1) Then, on the wild side...I mean the client side, you can conditionally assign that value to an element via jQuery. e.g., if you want to put that HiddenField value in a textbox (input text) element with an ID ending in "boxemailsection1", you can do so this way:

JavaScript
$(document).on("click", '[id$=rbPaymentForSelf]', function () {
    if (this.checked) {
        $('[id$=boxemailsection1]').val(function () {
            return $('[id$=hfuseremail]').val();
        })
    }
});

This assumes the radio button you need to respond to has an ID ending in "rbPaymentForSelf". YCMV (Your Code May Vary).

This works in my Sharepoint 2010 app; I assume it will work in any C#/jQuery type of app (various versions of Sharepoint, ASP.NET of various flavors, etc.) but don't Sioux me if it doesn't.

*

As to the pain nuts can suffer -- and that through no fault of their own, just from being naturally nutty -- consider the almond (Prunus dulcis). When it is on high, ensconced in its ancestral arbor, it is an almond, with the "l" sonically obvious (verbally expressed); when it falls to earth, though - anon and alas! - it gets the "l" knocked out of it, and becomes an amond (silent "l" -- silent because that formerly proud and stately character (which is sometimes confused with the integer "1") has been bounced to perdition).

The explanation directly above can be accepted as tangible evidence that Asterisks are Considered Harmful. After all, what is an Asterisk but a "GoTo" directive?

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)