I am using the below code to assign the value to a hidden control.But in code behind i can't get the value of the hidden control. Please help me to get this.I tried more time.
Script
=======
<script type="text/javascript">
function load_value() {
var val = document.getElementById('<%= hf_xml.ClientID %>');
val.value= "hai";//Whatever i want
alert(val.value);//alert message show with text hai
}
window.onload = load_value;
</script>
<asp:HiddenField ID="hf_xml" runat="server" />
Code Behind
===========
protected void Page_Load(object sender, EventArgs e)
{
string value = hf_xml.Value;//Always Empty
}
There is nothing really missing/incorrect in your code. Try to understand the sequence of events that happen.
Window.Onload is expected to get executed when the Page finishes loading. Whereas Page_Load is expected to be called earlier as the Page is still under process.
And this is indeed happening. As verified using debug symbols, the Page_Load is called first and the window.onload method will be called later. This is why your HiddenField is showing empty value.
Also, as expected, for the very first time when page is requested, HiddenField value will be Empty, but on next postback onwards, Value will be set for this HiddenField.
You should not use innerHTML on input controls
Use value instead
var val = document.getElementById('<%= hf_xml.ClientID %>');
val.value = "hai";//Whatever i want
are you trying to get the value before posting to server ?? means you cant access the value before posting to server(means on button click or some server side events)
put a asp:button on form and check the value after clicking the button
Related
A button on html page redirect to aspx page with window.open() command.
There are certain data on the html page which i want on server-side of the aspx page before page_load executes.
following is my code on the html page which redirects to the aspx page
var win = window.open('mypage.aspx','_self');
win.args=this.Args;
following is my code on aspx page which tries to catch the data passed from the html page
<script type='text/javascript'>
var readyStateCheckInterval = setInterval(function () {
if (document.readyState === "loading") {
$('#hdnArgs').val(window.args);
clearInterval(readyStateCheckInterval);
}
}, 100);
</script>
<input type='hidden' id='hdnArgs' runat='server'/>
Following is the code on the aspx.cs file which tries to read the hidden variable's value which has been set from the data of the html page
protected void Page_Load(object sender, eventargs e)
{
string data = hdnArgs.value; //this is always null
}
But what I get is always 'null'.
The readyStateCheckInterval sets the hidden variable value after the page_load event is completed.
I want the value of hidden variable before page_load.
How can I get that?
Its not possible to set value of any control before page life cycle finish.
let me explain you..
You try to set value on hdnArgs but In Page lifecycle control only generate and send it to browser only after finish Page_init,Page_Load,Page_Load_Complete
All those methods..
So,When you try set args value to hdnArgs using $('#hdnArgs').val(window.args); Page_load event already completed..
Solution
I think you need to pass value as a QueryString to get Value in Page_load
var win = window.open('mypage.aspx?Args='+this.Args,'_self');
and In ASPX page
protected void Page_Load(object sender, eventargs e)
{
string data = Request.QueryString["Args"];
}
Also you can send data using Page Postback if you have large data.
To confirm:
hdnArgs is on the starting page
starting page opens a new page in a window
when that page is opening (but not complete, which will hopefully happen when you happen to look at it at 100ms intervals... it won't if it's quicker than that), input#hdnArgs is updated to the a value from the opened page
The Page_Load is on the starting page
You want the start page Page_Load to get a value from the popup
You'll need to review the lifecycle of asp.net pages, eg: https://msdn.microsoft.com/en-gb/library/ms178472%28v=vs.100%29.aspx
By the time the start page even thinks about processing any javascript, the Page_Load of the startup page is long gone.
Perhaps, in the Page_Load, you could load the new page directly eg with
var content = new System.Net.WebClient().DownloadString(contentUrl);
and parsing it for the #hvnArgs
I have <td id="StatusPreview" runat="server"></td> and it gets populated by a js function by:
document.getElementById('StatusPreview').innerHTML = Ext.getCmp('TYComboEdit').getRawValue();
Now, I would like to change the content of the td in c# when a button is clicked.
I created the following method:
protected void hiddentoggletofrenchBackend(object sender, DirectEventArgs e)
{
this.StatusPreview.InnerHtml = "aaaaa";
}
It does not change the content on the td. However, if I place an alert after setting the InnerHtml it alerts aaaaa even though the td content has not changed to reflect this. If I place an alert before setting the InnerHtml the alert is blank.
How can I change the InnerHtml of the div?
Thank you!
UPDATE:
If I change the html to <td id="StatusPreview" runat="server">q</td> the alert shows q if it is placed before setting InnerHtml, and switches to aaaaa if placed after.
It is as if InnerHtml is taking the value on pageload, not the current value.
To update an ASP.NET control during a DirectEvent, you should call the .Update() method.
protected void hiddentoggletofrenchBackend(object sender, DirectEventArgs e)
{
this.StatusPreview.InnerHtml = "aaaaa";
this.StatusPreview.Update();
}
Adding runat=server to a td element turns it into a HtmlTableCell control. The relevant property to set the inner text on this control is InnerText.
As this is a server side control, any change is only going to happen after postback to the server. That would mean the entire page is reloaded and re-rendered. You can examine requests to the server and the server responses with the free tool Fiddler. Assuming a postback is actually happening, are you sure you're not overwriting the new inner text with JavaScript which runs on page load?
Do you even need to do a postback for this? If "aaaaa" is not a placeholder for what will become a database or some other lookup, I would render the alternate text into a hidden div or into some JavaScript and do the text change entirely in JavaScript.
I use hidden input fields to pass values form my javascript to the code behind. This works great but when I try to clear the fields from the code behind this doesn't work.
<input type="hidden" id="iRowNumberTblOne" name="iRowNumberTblOne" value="" runat="server"/>
I tired to do it by a few ways but they all don't work.
This is the easiest way and most logic but it doens't want to clear the values
iRowNumberTblOne.Value = "";
I even made a javascript, so the values would be cleared on the client side.
The alert comes up the first time "at startup" but after a postback it seems like the code behind doesn't find the javascript again.
<script type="text/javascript">
function clearInputFileds() {
alert('test');
document.getElementById("ctl00_contentHolder_iSiteAlias").value = "";
document.getElementById("ctl00_contentHolder_iServiceName").value = "";
document.getElementById("ctl00_contentHolder_iRowNumberTblOne").value = "";
document.getElementById("ctl00_contentHolder_iRowNumberTblTwo").value = "";
}
</script>
This is the code I use in the codebehind
Page.ClientScript.RegisterStartupScript(GetType(), "", "clearInputFileds();", true);
Do you have any idea why these methods doesn't work? Maybe know a better way to clear this fields?
EDIT:
The input fields get filled by a javascript function. This function gets runs onClick.
function setClickedValues(siteAlias, serviceName, rowNumberTblOne, rowNumberTblTwo) {
document.getElementById("ctl00_contentHolder_iSiteAlias").value = siteAlias;
document.getElementById("ctl00_contentHolder_iServiceName").value = serviceName;
document.getElementById("ctl00_contentHolder_iRowNumberTblOne").value = rowNumberTblOne;
document.getElementById("ctl00_contentHolder_iRowNumberTblTwo").value = rowNumberTblTwo;
}
This can be done in the code behind. But it is important to do it at the right time in the ASP.Net Application Livecycle. Take a closer look at:
ASP.NET Page Life Cycle Overview
Understanding ASP.NET View State
Usually you (re)set the value in the click event handlers of your submit button or in the LoadComplete event. If you do it before, the value will be overwritten at the time the ViewState is restored.
The following image is extremly usefull when working with ASP.Net pages and ViewState:
(Source: http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.100%29.aspx)
BTW: It is a very bad idea to reset the value in client code with hard coded ID's as they are subject to changes.
Since all of those are server-side elements (you have them as runat="server") the easiest way to clear the values is simply to do:
elementID.Value="";
On all of them after postback. If you are saying that the values are not being cleared after doing the above, it's probably because you are not checking if(!IsPostback) before executing the function that populates the values in the first place.
Your client side code should also work but it's probably failing because your last parameter to the RegisterStartupScript is true, which indicates that the <script> tags ought to be added. This may cause a problem because your function is already enclosed in <script> tags so the last true parameter is not needed in this case.
I have following JavaScript function, Which call Jquery JSON function and get the DateTime with respect to timezone. This works fine.
<script type="text/javascript">
function JSFunctionName() {
$(document).ready(function () {
var timezone = "US/Central";
$.getJSON("http://json-time.appspot.com/time.json?tz=" + timezone + "&callback=?",
function (data) {
if (data.hour < 12) {
//alert(data.hour + ':' + data.minute); // want to return this value data.hour + data.minute
//document.getElementById('<%=HiddenField1.ClientID %>').value = data.hour + ':' + data.minute;// this does not work
}
})
});
}
</script>
Now I am calling this Javascription function in Code behind on onclick of button
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Code behind
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "JSFunctionName();", true);
// here I need the DateTime value that is get from JSON
//Response.Write(HiddenField1.Value);
}
How can I return the value from Javascript to code behind immediate after call of Page.ClientScript.RegisterStartupScript
Please note I have try to set the value in HiddenField, but its not working. you can see in the comment.
Any idea or alternative solution will be appreciated.
Thanks
You can't do this without posting back to the server. The reason for this is that javascript executes on the client, and it will only execute after the page has left the server.
I assume this is a contrived example, but in this specific case, if you want to have the same information available on the client and server, you need to compute it on the server, and pass that out to the client.
If this isn't possible, you'll need to create a webservice, but that will have to handle the response asynchronously.
You can use ajax call to server from the javascript function or you may put another button on the form, hide it with style and cause click on this button after you set up calculated value to the hidden field in the JSFunctionName function.
Your problem is that the following line:
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "JSFunctionName();", true);
doesn't actually "execute" the Javascript funciton. It just adds the
JSFunctionName();
to the page in a script block, to be executed after your code has completed, and the page has loaded.
Rather than "calling the Javascript" from your button-click event, you could set the "OnClientClick" property of the button to "JSFunctionName()":
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" OnClientClick="JSFunctionName();" />
This will cause the JSFunctionName to fire before the postback happens. You can then set up your JSFunctionName() method to return true when it's done, which will then fire the postback.
You will then be able to access the value of HiddenField1 from the server-side click handler.
i have a popup that is getting displayed when Save button is clicked. The popup has 2 buttons. Yes and No. No should cancel the popup
and yes should take you to function in the code-behind say, btnSave_Click(object sender, Eventargs e). How is it possible. Could someone help me, i am new to Javascript.
Below is the code where i am showin the popup.
var mdlPopup = $find('<%= ModalPopupExtendersavechanges.ClientID %>');
if(mdlPopup)
{
mdlPopup.show();
}
To do this you will need to set your server side function as a web method like this:
Add to the top of your code behind:
using System.Web.Services;
using System.Web.Script.Services;
Then decorate your method with these attributes:
[WebMethod(), ScriptMethod()]
public static void btnSave_Click(Object sender)
{
//Stuff
}
To call this from the client side (Javascript) do this:
PageMethods.btnSave_Click(this,btnSave_Click_Finished);
You can place that in a client click event. The first argument is the sender parameter, the second is the javascript function to call when the server side method has completed.
You can't call server side code from JavaScript directly. Make a postback or fire a XHR (AJAX) request in the background.
I think it is possible for you to acess the serverside script by using javascript.
__doPostBackis a function which is behind the asp postback and this function is called when a button is clicked or dropdown value is changed.
For more details pls refer to [this.][1]
All you need is to place a <asp:Button ID="btnSave" runat="server" onClick="btnSave_Click" /> in the form and in the javascript (ie button click function) just call the __doPostBack('<%= btnSave.UniqueID %>', '');
So it will calls the serverside function.(btnSave_Click)
Notice that you need to give '<%= btnSave.UniqueID %>' as the firstargument.
The above will works as similar to a server button click
The another way is to make a post or ajax using jquery.post or jquery.ajax it is possible to send request asynchronously to the server.Here you want to pass some query string and call the appropriate function in the page_Load
This will do without any postback
One another method is to use PageMethods from clientside by defining a static WebMethod
[1]: http://msdn.microsoft.com/en-us/library/aa720099%28vs.71%29.aspx/"Call serverside function from clientside"
I hope any one of these will solve your problem
the Yes button should be an asp.net control with a server-side handler
markup
<asp:button id="yesButton" runat="server" onclick="yes_click" />
codebehind
void yes_click(object sender, EventArgs e) {
// TODO your thing here.
}
the other buttons can be standard html inputs with javascript event handlers. if you are using javascript to alter element style, the changes won't persist across a postback- when the yes button submits and the page reloads, the popup won't be visible.