Wednesday, July 25, 2007

How to access the variable of SourceView (.aspx) in CodeBehind page (.aspx.cs)

If you want to access the value of a variable in the code behind page (.aspx.cs), which is declared in the .aspx. You can do it this way:

Eg.: The following code in .aspx page has a Javascript function which has a variable declared. The variable is used to store the value returned as a result of the user clicking the "Confirm Box" on client side. So, here the function gets called on the "OnClientClick" event. This event is one of the useful additions to asp.net.
Here, the "CreateNewEvent()" function gets called on "OnClientClick" event

==============================================================
head runat="server"
titleUntitled Page /title
script language="javascript" type ="text/javascript"
function CreateNewEvent()
{
var newHdfield = document.createElement("INPUT");
newHdfield.setAttribute('id','pageTitle');
newHdfield.setAttribute('name','pageTitle');
newHdfield.setAttribute('type','hidden');
newHdfield.value = confirm("do u wanna do it ?");
document.getElementById("form1").appendChild(newHdfield,form1);
}
/script
/head
body
form id="form1" runat="server"
asp:Button ID="Button1" OnClientClick="CreateNewEvent()" runat="server" Style="z-index: 100; left: 40px; position: absolute;
top: 109px" Text="Button" /
/form
/body
================================================
.aspx.vb page might look like this:
--//On button click, in the server side event, we are just capturing the value of the variable defined in the Javascript function in the .aspx page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a As String = Request.Form("pageTitle")
End Sub
================================================

So, now use the value of 'a' for our purposes in the code-behind page.

Note 1: as always, the "<" and ">" tags for the html code in the .aspx page have been removed to render the content in the blog. Please put them at the appropriate positions.

Note 2: I had to struggle for long for not making the variable (hidden field) as a child node to the Form. Because when we try to access the variable in the code-behind page using Form(integer or string value), it shows only the children of Form element in the array. So, DO NOT FORGET to make the variable (field) as a child to the FORM element.

Note 3: I did not encounter it but read on a different blog that both the 'id' and 'name' attributes should be set and they should be same. --- Try it. I do not guarantee anything from my side. I just followed their instruction.

Related Link: http://forums.asp.net/p/1057915/1511865.aspx

1 comment:

Unknown said...

need dba stuff dude...I thik u can guess hehe