Link to home
Start Free TrialLog in
Avatar of steelsanc
steelsanc

asked on

Having problems either sending or receiving values from a hidden field.

So, I'm fairly new to asp.net and I wanted to pass from values from a javascript function (called in code behind) to the server side.  I have the javascript function in a .js file.  Upon further research online, I found a way through hidden fields.  I declared a hidden field and the code looks like it's fine (obviously it's not) but it is still not receiving the values from the hidden field.  Can you all take a look at my code and tell me what is wrong?
code in aspx:
 
<asp:HiddenField ID="ContentType" runat="server" />
 
 
code behind:
 
public partial class _Default : System.Web.UI.Page 
{
    public void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["SalesDBConnectionString"].ToString();
        con.Open();
 
        SqlDataReader read;
 
        SqlCommand cmdtest = new SqlCommand("SELECT * FROM Details_Instructor", con);
        cmdtest.CommandType = CommandType.Text;
        read = cmdtest.ExecuteReader();
 
        ArrayList myArrList = new ArrayList();
 
        try
        {
            while (read.Read())
            {
                myArrList.Add(read["InstructorPhone"].ToString());
            }
 
            for (int i = 0; i <= 10; i++)
            {
                var testString = myArrList[i].ToString();
                TextBox1.Text += (testString + '\n');
                
                ClientScript.RegisterClientScriptBlock(typeof(Page), "formValidation", "isValidPhoneNumber('" + testString + "', true, true)", true);
 
                string testHiddenField = Request.Form["ContentType"];
 
                TextBox3.Text += testHiddenField;
            }
        }
        catch (SqlException ex)
        {
            TextBox2.Text = ex.ToString();
        }
        finally
        {
            read.Close();
            con.Close();
            TextBox3.Text += "End";
        }
    }
 
    public void Button1_Click(object sender, EventArgs e)
    {
 
    }
}
 
 
last part of code from the javascript file where I try to pass a value (newPhone):
 
        var myTextBox = document.getElementById("ContentType"); 
        myTextBox = newPhone;
 
Am I doing something wrong with how I assign a value to the hidden field?

Open in new window

Avatar of tpsl
tpsl
Flag of India image

string testHiddenField = Request.Form["ContentType"].ToString();


var myTextBox = document.getElementById("ContentType");
myTextBox.value = newPhone;
Avatar of steelsanc
steelsanc

ASKER

I've tried this and this is the error I receive from the code behind page:

"NullReferenceException was unhandled by user code
Object reference not set to an instance of an object."

any other ideas?
Can u rename ContentType

to something else like hdnContentType and then try?

And which particular line gives this error of object reference
I think it sould be like this
string testHiddenField = ContentType.Value;
 
and JS should be
var myTextBox = document.getElementById("ContentType"); 
myTextBox.value = newPhone;

Open in new window

What would renaming it change (besides the name)?  ...anyway, I did that and of course the same error came up.  The line in particualr that flags the error is the line you suggested:  

string testHiddenField = Request.Form["ContentType"].ToString();

So for the heck of it, I took out "ToString()" and it went through but threw an error in the .js file at the line:

myTextBox.value = newPhone;

The error reads:  "Microsoft JScript runtime error: 'null' is null or not an object"
So try your javascript like this. If the Javascript is in a seperate file then copy the ID of the hidden field from the HTML source (from browsers view source option) and use that ID
ar myTextBox = document.getElementById("<%=ContentType.ClientID%>"); 
myTextBox.value = newPhone;

Open in new window

sunithnair, I've tried the code you suggested in the code behind page and I think that works but then it throws an error on the javascript page:

'null' is null or not an object

at the line with:  myTextBox.value = newPhone;

So I took out ".value" and it goes through but the output in the textbox is empty.  I started stepping through the js page and it all looks fine.  It looks like myTextBox gets the value.  Could the problem be from the aspx.cs page?
Is there a masterpage involved?

If yes... then Request.Form["ContentType"] won't work because the id generated while using masterpages would be different.

So it's advisable to use ContentType.value as suggested by sunithnair.

And the client id would also be different as suggested by sunithnair. Please view the html source generated by clicking on view source in the browser


The right way to do it is myTextBox.value = newPhone; otherwise your textbox will not have the value set. You are getting error with null because myTextBox is null. This happens because your document.getElementById("ContentType") returns null value and this is because your ContentType is a server control and the Id of the server control when rendered as HTML might not be the same as the actual Id of the control. The id changes when you have the control inside another container controls lilke master page, panels, data grids etc. If the Javascript is in a seperate file then copy the ID of the hidden field from the HTML source (from browsers view source option) and use that ID.
tpsl, there is no master page involved.  I am using ContentType.value and it seems fine but the output is empty.  So I stepped through and indeed testHiddenField is empty.  I'm wondering how the value is getting lost.
Just when r calling the javascript function that assigns value to hidden field
I really appreciate the help guys.  So I took a look at the source code and saw the two IDs:  __EVENTVALIDATION and __VIEWSTATE

Which and where should these be used?
tpsl, to answer your question:  It's on line 36 of the code snippet I posted.
Dont worry about those hidden fields because those are generated by ASP.NET automatically for tracking viewstate and event validation. Please see if you can see any other hidden field which looks something like this GridView1_ctl03_ContentType
Hmm. that seems to clear the confusion a bit.

What I would suggest is this.

what you are doing is passing a teststring to a javascript function. The javascript function in turn assigns it to a hidden variable. Then u r once again fetching it from the hidden variable.

Why not just assign the value like this
TextBox3.Text += testString;

If u are performing any operations in javascript you could very well perform these in code behind itself.

The problem with your code is you are assigning the value in javascript. But javascript will be called once the page is rendered entirely. You are fetching the value from the hidden field even before the page is rendered. Hence it will give u blank value
sunithnair, I've looked through the source code and I do not see any other hidden fields besides the one I mentioned.  Perhaps I'm looking at the wrong source code at the wrong time?

tpsl, the javascript function formats the inputted value.  What I want to get is the formatted variable.  If I use:  TextBox3.text += testString;
I believe that would give me the unformatted variables.

Would it be easier to just not reference the js file at all and just have the function on the asp page?
Yes it would be easier in that case and you can do it like this in that case
var myTextBox = document.getElementById("<%=ContentType.ClientID%>"); 
myTextBox.value = newPhone;

Open in new window

sunithnair, I've placed the javascript function in the aspx page and I'm still getting that null error at the line:

myTextBox.value = newPhone;

... now in the aspx page.    I'm pretty much stuck now.  

can you please paste your code here?
This is basically my code in the aspx page:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>DBTest</title>
    <style type="text/css">
        #TextArea1
        {
            height: 350px;
            width: 240px;
        }
        #TextArea2
        {
            height: 350px;
            width: 240px;
            margin-left: 245px;
            margin-top: 0px;
        }
    </style>
    <script type="text/javascript">
    
function isValidPhoneNumber (elem, blnPrompt, blnAllowEmpty)
{
    if (typeof(blnPrompt) == 'undefined' ) blnPrompt = true;
	if (typeof(blnAllowEmpty) == 'undefined' ) blnAllowEmpty = true;
	
	var str = elem;
	
	var phoneError = /[^extnsio\d\(\)\-\.\s\+\:\;\,]/gi;
	
	if(!blnAllowEmpty && !isNotEmpty(elem, blnPrompt)){
		return false;
	}
	if(blnAllowEmpty && str == ""){
		return true;
	}
	
	if (substr_count(str, '(') != substr_count(str, ')'))
	{
	    if(blnPrompt){
			alert("Please check your phone number");
		}
		elem.select();
		elem.focus();
		return false;
	}
	
    function StringBuffer() 
    { 
        this.buffer = []; 
    } 
 
    StringBuffer.prototype.append = function append(string) 
    { 
        this.buffer.push(string); 
        return this; 
    }; 
 
    StringBuffer.prototype.toString = function toString() 
    { 
        return this.buffer.join(""); 
    }; 
 
    var plusAppend = new StringBuffer();
    
    var cleanPhone = str;
	
	// cleans up the phone number and takes out all characters not a number
	var cleanPhoneNonNumeral = cleanPhone.replace(/[^\d,]/gi, "");
	// phone number length
	var phoneDigits = cleanPhoneNonNumeral.length;
	
	var newPhone = "";
	var valid = false;
	
	switch(phoneDigits)
	{   
	    case 10:
	    {
	        var areaCodePhone = /\(?[0-9]{3}\)?(.|-| ){0,5}[0-9]{3}(.|-| )?[0-9]{4}/;
 
	        if(str.match(areaCodePhone))
	        {
	            valid = true;
	            
	            newPhone = plusAppend + "(" + cleanPhoneNonNumeral.substring(0,3) + ") " + cleanPhoneNonNumeral.substring(3,6) + "-" + cleanPhoneNonNumeral.substring(6,10);
	            break;
	        }
	    }
	    
	    default:
	    {   
	        alert("Please double-check the phone number you've entered");
	        return false;
	    }
	}
	
	if(valid)
	{ 
	    elem = newPhone;
        
        var myTextBox = document.getElementById("ContentType"); 
        myTextBox.value = newPhone;
    } 
    else
    {
        elem = str;
    }
 
	return true;
}
 
function substr_count( searchString, subSearchString, offset, length )
{
    var pos = 0, count = 0;
 
    searchString += '';
    subSearchString += '';
    if(isNaN(offset)) offset = 0;
    if(isNaN(length)) length = 0;
    offset--;
 
    while( (offset = searchString.indexOf(subSearchString, offset+1)) != -1 )
    {
        if(length > 0 && (offset+subSearchString.length) > length)
        {
            return false;
        } 
        else
        {
            count++;
        }
    }
 
    return count;
}
</script>
    
</head>
<body>
    <form id="form1" runat="server">
    <asp:HiddenField ID="ContentType" runat="server" />
    <div>
    </div>
    <p style="margin-top: 2px">
        <asp:TextBox ID="TextBox1" 
            runat="server" Height="400px" TextMode="MultiLine" Width="250px" 
            ReadOnly="True"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server" Height="400px" TextMode="MultiLine" 
            Width="250px" ReadOnly="True"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server" Height="400px" Width="250px" 
            ReadOnly="True" TextMode="MultiLine"></asp:TextBox>
    </p>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    </asp:UpdatePanel>
    <p style="margin-top: 2px">
        <asp:Button ID="btnStart" runat="server" onclick="Button1_Click" Text="Start" />
    </p>
    </form>
</body>
</html>

Open in new window

The problem is the javascript gets called  before your page is fully loaded which means the hidden field is not available when the javascript is executed. I have modified your code like this (also removed the database stuff. Try this one
ASPX
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestForm.aspx.cs" Inherits="TestForm" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>DBTest</title>
    <style type="text/css">
        #TextArea1
        {
            height: 350px;
            width: 240px;
        }
        #TextArea2
        {
            height: 350px;
            width: 240px;
            margin-left: 245px;
            margin-top: 0px;
        }
    </style>
    <script type="text/javascript">
    
function isValidPhoneNumber (elem, blnPrompt, blnAllowEmpty)
{
    if (typeof(blnPrompt) == 'undefined' ) blnPrompt = true;
	if (typeof(blnAllowEmpty) == 'undefined' ) blnAllowEmpty = true;
	
	var str = elem;
	
	var phoneError = /[^extnsio\d\(\)\-\.\s\+\:\;\,]/gi;
	
	if(!blnAllowEmpty && !isNotEmpty(elem, blnPrompt)){
		return false;
	}
	if(blnAllowEmpty && str == ""){
		return true;
	}
	
	if (substr_count(str, '(') != substr_count(str, ')'))
	{
	    if(blnPrompt){
			alert("Please check your phone number");
		}
		elem.select();
		elem.focus();
		return false;
	}
	
    function StringBuffer() 
    { 
        this.buffer = []; 
    } 
 
    StringBuffer.prototype.append = function append(string) 
    { 
        this.buffer.push(string); 
        return this; 
    }; 
 
    StringBuffer.prototype.toString = function toString() 
    { 
        return this.buffer.join(""); 
    }; 
 
    var plusAppend = new StringBuffer();
    
    var cleanPhone = str;
	
	// cleans up the phone number and takes out all characters not a number
	var cleanPhoneNonNumeral = cleanPhone.replace(/[^\d,]/gi, "");
	// phone number length
	var phoneDigits = cleanPhoneNonNumeral.length;
	
	var newPhone = "";
	var valid = false;
	
	switch(phoneDigits)
	{   
	    case 10:
	    {
	        var areaCodePhone = /\(?[0-9]{3}\)?(.|-| ){0,5}[0-9]{3}(.|-| )?[0-9]{4}/;
 
	        if(str.match(areaCodePhone))
	        {
	            valid = true;
	            
	            newPhone = plusAppend + "(" + cleanPhoneNonNumeral.substring(0,3) + ") " + cleanPhoneNonNumeral.substring(3,6) + "-" + cleanPhoneNonNumeral.substring(6,10);
	            break;
	        }
	    }
	    
	    default:
	    {   
	        alert("Please double-check the phone number you've entered");
	        return false;
	    }
	}
	
	if(valid)
	{ 
	    elem = newPhone;
        
        var myTextBox = document.getElementById("ContentType"); 
        myTextBox.value = newPhone;
    } 
    else
    {
        elem = str;
    }
 
	return true;
}
 
function substr_count( searchString, subSearchString, offset, length )
{
    var pos = 0, count = 0;
 
    searchString += '';
    subSearchString += '';
    if(isNaN(offset)) offset = 0;
    if(isNaN(length)) length = 0;
    offset--;
 
    while( (offset = searchString.indexOf(subSearchString, offset+1)) != -1 )
    {
        if(length > 0 && (offset+subSearchString.length) > length)
        {
            return false;
        } 
        else
        {
            count++;
        }
    }
 
    return count;
}
</script>
    
</head>
<body onload="ValidateForm();">
    <form id="form1" runat="server">
    <asp:HiddenField ID="ContentType" runat="server" />
    <div>
    </div>
    <p style="margin-top: 2px">
        <asp:TextBox ID="TextBox1" 
            runat="server" Height="400px" TextMode="MultiLine" Width="250px" 
            ReadOnly="True"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server" Height="400px" TextMode="MultiLine" 
            Width="250px" ReadOnly="True"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server" Height="400px" Width="250px" 
            ReadOnly="True" TextMode="MultiLine"></asp:TextBox>
    </p>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    </asp:UpdatePanel>
    <p style="margin-top: 2px">
        <asp:Button ID="btnStart" runat="server" onclick="Button1_Click" Text="Start" />
    </p>
    </form>
</body>
</html>
 
 
CODEBEHIND
 
public partial class TestForm : System.Web.UI.Page
{
    public void Page_Load(object sender, EventArgs e)
    {
        try
        {
            var js = "function ValidateForm(){\n";
            for (int i = 0; i <= 10; i++)
            {
                var testString = "(123) 456-7890";
                TextBox1.Text += (testString + '\n');
                js += "isValidPhoneNumber('" + testString + "', true, true)\n";
 
                string testHiddenField = ContentType.Value;
 
                TextBox3.Text += testHiddenField;
            }
            js += "}";
                ClientScript.RegisterClientScriptBlock(this.GetType(), "formValidation", js , true);
        }
        catch (Exception ex)
        {
            TextBox2.Text = ex.ToString();
        }
        finally
        {
            TextBox3.Text += "End";
        }
    }
 
    public void Button1_Click(object sender, EventArgs e)
    {
 
    }
}

Open in new window

sunithnair, thanks for your response.

I've tried the code and I added the db access and it looks to be fine but the output I'm needing is still null.  In TextBox1, where I have the output of the unformatted numbers, it looks fine but TextBox3 is still null.  I've stepped through the javascript function and also added an alert, just to see what value myTextBox gets and this is the popup I get:

myTextBox = [object]

I'm wondering if there's something wrong with how I'm passing the value to the hidden field?
Code Behind:
 
public partial class _Default : System.Web.UI.Page
{
    public void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["SalesDBConnectionString"].ToString();
        con.Open();
 
        SqlDataReader read;
 
        SqlCommand cmdtest = new SqlCommand("SELECT * FROM Details_Instructor", con);
        cmdtest.CommandType = CommandType.Text;
        read = cmdtest.ExecuteReader();
 
        ArrayList myArrList = new ArrayList();
 
        try
        {
            while (read.Read())
            {
                myArrList.Add(read["InstructorPhone"].ToString());
            }
 
            var js = "function ValidateForm(){\n";
            for (int i = 0; i <= 10; i++)
            {
                var testString = myArrList[i].ToString();
                TextBox1.Text += (testString + '\n');
                js += "isValidPhoneNumber('" + testString + "', true, true)\n";
 
                var testHiddenField = ContentType.Value;
 
                TextBox3.Text += testHiddenField;
            }
            js += "}";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "formValidation", js, true);
        }
        catch (Exception ex)
        {
            TextBox2.Text = ex.ToString();
        }
        finally
        {
            TextBox3.Text += "End";
        }
    }
 
    public void Button1_Click(object sender, EventArgs e)
    {
 
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of sunithnair
sunithnair

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I have that line in javascript and it's still giving me null.  I pretty much used what you replied with earlier.