I tried the following code but did not succeed.It would be great if you could guide me. I was trying to test using a simple "Hello". In the actual program I would assign a string value to the hidden field.
I get an Alert box ( using this to test whether the value is accessible in javascript ) but with no values.
Server Side
ivar.Value = "Hello"
Javascript
<script>
function getval() {
var v = document.getElementById('<%= ivar.ClientID%>').value;
alert(v)
}
</script>
Form
<asp:Button ID="Button1" runat="server" Text="CALCULATE" onclientclick="getval()" />
<asp:HiddenField ClientIDMode="static" id="ivar" runat="server" Value=""/>
Let us say you have a public variable on server side:
public string iVar = "Hello";
You can directly add it to your javascript as below:
<script>
function getval() {
var v = <%=iVar%>;
alert(v);
}
</script>
Hope this helps.
Your call to find the client id in your script block may be trying to find the hidden field before it exists. try moving the script to the bottom of the page just before you close your body tag and see if that helps.
Related
I want to pass data from back-end to front-end and front-end to back-end so far I have tried like below
back-end to front-end :-
back-end (.aspx.cs):-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
}
front-end (.aspx):-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert(amt); // data coming
</script>
</form>
</body>
The above example is working fine but while passing the value from front-end to back-end I'm getting the null("") value (for this concept I have read this article)
front-end to back-end :-
front-end (.aspx) :-
<body>
<form id="form1" runat="server">
<script type="text/javascript">
var amt = "<%=amt%>";
alert("amt :- " + amt);
function getval() {
var keyid = "1234";
document.getElementById('key_id').value = keyid;
alert(document.getElementById('key_id').value);
alert('hit');
window.location.href = "http://localhost:49855/ValuePassig.aspx";
}
//alert(amt);
</script>
<input id="key_id" runat="server" type="hidden" name="key_id_1" />
<input type="button" id="btn" value="click" runat="server" onclick="getval()" />
</form>
</body>
back-end(.aspx.cs) :-
public string amt;
protected void Page_Load(object sender, EventArgs e)
{
amt = "100";
//I'm getting the null("") value
//string kId = this.Request["key_id_1"];
//string kId = Request.Form["key_id_1"];
string kId = key_id.Value; //Initially the value come null(acceptable) and next I'm clicking on the "click" button at that time null value should not come(but coming)
Response.Write(kId);
}
I did my best so far to achieve this concept and I don't why I'm getting a null value because, I have followed the article also(above mentioned link) to achieve this
concept
Suggest me where I did the mistake to pass the value from front-end to back-end and how to achieve this
Please give me your best suggestions.
Note :- I have changed the code for better understanding that is button added and when I click on the button the hidden value should come back-end.
Ok, so we want to have some value - set in code behind cs, to set/pass/have some value for use in the client side js code.
And of course in the js code, we want use of that value, and ALSO to be able to change that value, and then upon actions, or code behind, we want that value passed back to the code behind.
First up, don't use a server side expression to "set" that value for use in the js code. The reason of course then you don't have a easy way to pass back and have use of that change value in the code behind.
You can freely change the var in js code, but you really don't have a easy/nice way to get that value back to the code behind (so that <%= %> expression is a one way street to the client side.
There are a LOT of ways to do this, but probably best is to drop in a hidden field control (as per your question title)..
You can also use a hidden text box, but might as well use the hidden field.
So, lets on page load (and ONLY first page load - like all setup on the page should be inside of the !IsPostBack code block - all web pages quite much need this !IsPostBack code block).
And bonus?
the Hidden field control has automatic view state. (that means the value will persist on page post-backs).
So, lets drop in a server side button to "show" the value.
And THEN lets drop in a button (client side) to show the value, and ALSO to modify the value.
<asp:HiddenField ID="MyHotelName" runat="server" ClientIDMode="Static" />
<h3>Server side code</h3>
<asp:Button ID="cmdShowServer" runat="server" OnClick="cmdShowServer_Click"
Text="Show Hotel Name" CssClass="btn" />
<br />
<asp:Label ID="lblShow" runat="server" Text="Label"></asp:Label>
<h3>Client side code</h3>
<asp:Button ID="cmdShowClient" runat="server" Text="Show Hotel Name"
OnClientClick="ShowHotel();return false" />
<br />
<asp:Button ID="cmdChangeClient" runat="server" Text="Change Hotel Name"
OnClientClick="ChangeHotel();return false" />
<script>
function ShowHotel() {
alert("Hotel name = " + $("#MyHotelName").val())
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
$("#MyHotelName").val(sHotelNew)
}
</script>
And our code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MyHotelName.Value = "Zoo";
}
}
protected void cmdShowServer_Click(object sender, EventArgs e)
{
lblShow.Text = "Value of hotel = " + MyHotelName.Value;
}
So, we now have this:
Edit: Above used jquery.
Of course the js code above used jQuery.
however, we could assume pure js code, no jQuery.
so, the js code would then become this:
<script>
function ShowHotel() {
sHotel = document.getElementById("MyHotelName").value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById("MyHotelName").value = sHotelNew
}
</script>
I should also point out the "very" imprortant adding of clientidmode="static" for the hidden field. This will "prevent" asp.net system from changing the "id" used for the control, and as a result, the js code tends to be more "clean" and "easy" to reference controls.
If you don't want to use clientidmode=static for the hidden field, then the above code then becomes this:
hidden field thus is this: (no client id mode).
<asp:HiddenField ID="MyHotelName" runat="server" />
And now our code becomes this:
<script>
function ShowHotel() {
sHotel = document.getElementById('<%= MyHotelName.ClientID %>').value
alert("Hotel name = " + sHotel)
}
function ChangeHotel() {
sHotelNew = prompt("Enter new hotel value")
document.getElementById('<%= MyHotelName.ClientID %>').value = sHotelNew
}
</script>
So, I often will toss in a ClientIDMode="static" for the hidden field, as that makes the js code to get the hidden control less messy.
I want to pass java script function value to command argument of button and want to get in EditGuest data method of my cs page.
Here is the EditGeuest function
function EditGeuest(){
var gstDetails = document.getElementById('<%#cmbGuestName1.ClientID %>');
var guestID = gstDetails.value;
}
Here is the button code
<asp:Button ID="Editbtn" OnClientClick="EditGeuest() OnClick="EditGuestdata" CommandArgument=guestID runat="server" Text="Edit" />
You want to use this:
document.getElementById('Editbtn').CommandArgument = guestID
Your button tag must already contain the attribute CommandArgument with or without a value.
// text Box
<asp:TextBox ID="TextBox3" runat="server" BackColor="Silver"
BorderColor="Silver" ontextchanged="TextBox3_TextChanged"
style="margin-left: 6px" Width="154px"></asp:TextBox>
// Submit button
<asp:Button ID="Button6" runat="server" BackColor="Silver"
onClientclick='store_memID()' style="margin-left: 20px" Text="Submit"
Width="102px" Font-Bold="True" Height="28px" />
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
When I run the code and enter a value into the text box and then press the submit button:-
"Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined".
Else, if I remove the '.value' :-
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('TextBox3');
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
and then run the program, enter value in text box and press submit then i get :-
"TimeLine is displayed for: Null"
I have been looking into solving this problem. not sure whats going wrong...
Edit (fix):- Server Side ID for my text box is 'TextBox3' but this doesn't necessarily match up with the client side ID.
to get Client Side ID:- '<%=TextBox3.ClientID%>'
It's been a while since I wrote asp forms but it is likely that the id on the client side (in your browser) is not what you think it is. This is/was one of the major pitfalls of web forms in my mind (This may have been made simpler in version 4.0, you'll have to check that). You could use a css class (and use jQuery or similar to find your element) or inject the client side id into the java script e.g.;
<script type = "text/javascript">
// Function to caputure client-input- Member_ID.
function store_memID() {
var mem_ID = document.getElementById('<%=TextBox3.ClientID%>').value;
return confirm('TimeLine is displayed for: ' + mem_ID);
}
</script>
UPDATE: fixed case error in ClientID as pointed out in comments
You are using asp Text Boxes which are mostly used for server side code. The ID you place in the tag is not guaranteed to match the ID of the element rendered.
You will need to inspect your html in the browser to find the rendered ids. (Likely will look something like: ct100_TextBox3) and use that instead. Or, if you are not doing any server side coding, it would probably be best to convert your text boxes to <input /> fields, or <textarea />.
I have a hidden field in my form, I'm setting the hidden field's value on the server and trying to access this value from javascript,
I get the error: Unable to get value of the property 'value': object is null or undefined
If I view the source the hidden field value is set and the ID of the hidden field is the same as the ID I'm calling.
ASPX
var v = document.getElementById('hxValue').value;
<asp:HiddenField ID="hxValue" runat="server"/>
VB
hxValue.Value = "Value1"
I recall doing this before and it should be relatively simple but for some reason, i'm not getting it right.
Your code will work. For simple forms, just add
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
OR
you need to find the client id using
'<%=hxValue.ClientID%>'
Ok it appears my hidden field's value had not been set before the script had run, therefore receiving a null value. I had assumed that placing breakpoints on the server page load and the script would establish if the control was being set before the script ran, appears not.
Fixed as below:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript">
function GetHiddenValues() {
var v = document.getElementById('<%= hxValue.ClientID %>').value;
}
</script>
</head>
<body onload="GetHiddenValues() ;">
<form runat="server">
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
</form>
</body>
</html>
Thanks for all the assistance.
You can use innerText not value to retrieve the value of hxValue.
var v = document.getElementById('hxValue').innerText
If you were using jQuery you could also do
var v = $("#hxValue").val();
Try this
var v = document.getElementById('<%= hxValue.ClientID %>').value;
Problem is that Hidden Field is server side control and it's ID that you have given is a server side ID, you will have to get client side ID of that control to refer it in your client side JavaScript or Jquery.
Update
put this script at the end of your page, just before </body> something like this
<script type="text/javascript" language="javascript">
var v = document.getElementById('<%= hxValue.ClientID %>').value;
</script>
</body>
Try <asp:HiddenField ID="hxValue" runat="server" Value=""/>
Then call it by id and set value
I'm calling a partial postback from javascript like so:
function GetPolicyClick()
{"__dopostback('UpdatePanel1', 'PostCall')";}
It does 1/2 of what I need it to. It does call a partial postback, just for my UpdatePanel.
Now the tricky part. I'm trying (somehow) to reference the second argument of __dopostback in my code behind. This does not work:
Private Sub UpdatePanel1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdatePanel1.Load
Dim MyArg As String = Request("__EVENTARGUMENT")
End Sub
I just get an empty string.
Of course, what I'm trying to do might be completely wrong (as with everything else I try to do with ASP). I'm suspecting that my codebehind is grabbing the event argument from the page instead of the panel, but I really don't know, Any ideas?
If you want to put some value inside _EVENTARGUMENT you should do this with javascript before sending form by _doPostBack('UpdatePanel1','') because __EVENTTARGET is hidden field and in your html document it looks like this:
<input type="hidden" value="" id="__EVENTARGUMENT" name="__EVENTARGUMENT">
I recommend you to do something like this:
function setArgAndPostBack() {
var arg = document.getElementById('__EVENTARGUMENT');
var arg = document.getElementById("__EVENTARGUMENT");
arg.value = 'something you want to put to server';
__doPostBack('UpdatePanel1', '');
}
If you use jQuery it would be shorter:
function setArgAndPostBack() {
$("#__EVENTARGUMENT").val('something you want to put to server');
__doPostBack('UpdatePanel1', '');
}
If it doesn't work I would like to suggest you to put one hidden field inside Update panel:
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<ContentTemplate>
<asp:HiddenField ID="hdnData" value="" runat="server" />
<!-- your content goes here -->
</ContentTemplate>
</asp:UpdatePanel>
And then do the same work like above:
function setArgAndPostBack() {
//Here hidden field is filled with your data
$("#<%=hdnData.ClientID%>").val('something you want to put to server');
__doPostBack('UpdatePanel1', '');
}
In first scenario you are able to get __EVENTARGUMENT in server side:
String args = Request["__EVENTARGUMENT"];
If first scenario doesn't work you can use something like that:
String args = hdnData.Value;//This works even in Page_Load function.