updating javascript variable after .NET doPostBack fires - javascript

I'm trying to update a javascript variable whenever my vb.net page fires a "doPostBack" event which causes a .net session variable to update.
I tried adding this but it doesn't work.
<script>
var mySessionVariable = '<%= Session("monsterID")%>';
addToPostBack = function (func) {
var old__doPostBack = __doPostBack;
if (typeof __doPostBack != 'function') {
__doPostBack = func;
} else {
__doPostBack = function (t, a) {
if (func(t, a)) old__doPostBack(t, a);
}
}
};
$(document).ready(function () {
addToPostBack(function (t, a) {
mySessionVariable = '<%= Session("monsterID")%>';
});
console.log("mySessionVariable: ", mySessionVariable);
});
</script>
Even though the Session variable changes on the vb.net side after firing an event that does a "doPostBack", it remains the same both before and after the postback on the client side side.
MonsterVar1
MonsterVar1
Is there anyway to get this to work?
Thanks!

Wouldn't make more sense to have a Hidden Field instead of grabbing something from the session to make it work with JS on the page:
<asp:HiddenField id="HiddenField1" runat=Server />
JS
//document.getElementById('<%= HiddenField1.ClientID%>');
var value = document.getElementById("<%= Hiddenfield1.ClientID %>").value

Related

unable to get the value of button inside update panel

Team,
When I click on the first add template button then the download value disappear. .
window.onload = function() {
ddnameChange();
};
function ddnameChange() {
var e = document.getElementById("<%=ddltemplate.ClientID %>");
var ddnamevalue = e.options[e.selectedIndex].value;
if(ddnamevalue==2)
{
<%=btndownload.ClientID %>.value="Download RBH Template";
}
else if(ddnamevalue==3)
{
<%=btndownload.ClientID %>.value="Download VISTA Template";
}
else
{
<%=btndownload.ClientID %>.value="Download OD Template";
}
}
I am not able to get the second button value when i click on edit as well as all template button.I know it should be something reason like update panel that why the function is not calling I don't know how to solve it.
You have to add this in the method that handles the Async PostBack.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ddnameChange", "ddnameChange();", true);
When the Async PostBack occurs, everyting inside the UpdatePanel is rebuild and anything that has been altered by jQuery will be lost.

Calling a jquery function in code using vb.net

having a bit of an odd problem, the situation is a bit unique in that I want to show/hide a div in instances both server side and client side, as such I cant change it to a panel.
The current code I have to change its visiblity client side, which works, is:
$('#<%= txtSurname.ClientID%>').on('input', function hideControl() {
var current = $('#<%= txtSurname.ClientID%>').val();
var surname = $('#<%= hdnSurname.ClientID%>').val();
if (current == surname) {
$('#pnlReason').hide()
console.log('hiding');
} else {
$('#pnlReason').show()
console.log('showing');
}
});
When a user clicks a button, the page validates, and refreshes, and the panel is rendered invisible again. As such I want to run this code again on the page load so that if the two variables are still different when the page validation is run, the panel is still visible. This is what im using to call it serverside:
Page.ClientScript.RegisterStartupScript(Page.GetType(), "ShowHide",
"$(document.ready(hideControl()));", True)
When I try running it however, it says that hideControl is undefined, any ideas whats going wrong?
you could reorganise your jquery like this and once the page is refreshed, you can execute your function at the end of the document ready without the need for RegisterStartupScript():
//shorthand for document.ready
$(function () {
var hideControl = function() {
var current = $('#<%= txtSurname.ClientID%>').val();
var surname = $('#<%= hdnSurname.ClientID%>').val();
if (current == surname) {
$('#pnlReason').hide()
console.log('hiding');
} else {
$('#pnlReason').show()
console.log('showing');
}
}
$('#<%= txtSurname.ClientID%>').on('input', function () {
hideControl();
});
//call it at end of ready function:
hideControl();
};
Since hideControl is defined as anonynous function you can't access it. You have to define the function hideControl outside of the on event handler. Put the function within the script tags in the page not in a separate file:
<script>
function hideControl() {
var current = $('#<%= txtSurname.ClientID%>').val();
var surname = $('#<%= hdnSurname.ClientID%>').val();
if (current == surname) {
$('#pnlReason').hide()
console.log('hiding');
} else {
$('#pnlReason').show()
console.log('showing');
}
}
</script>
Then call the function like that at server side without the parenthesis:
Page.ClientScript.RegisterStartupScript(Page.GetType(), "ShowHide",
"$(document.ready(hideControl));", True)

Dynamically open a radwindow defined in Javascript

Objective:- From the server-side, I need to open a radwindow(defined in JavaScript of the aspx page) automatically on an IF condition.
Code used:-
In aspx page, I defined the radwindow as:-
<telerik:RadWindowManager Skin="WBDA" ID="AssetPreviewManager" Modal="true"
EnableEmbeddedSkins="false" runat="server" DestroyOnClose="true" Behavior="Close"
style="z-index:8000">
<Windows>
<telerik:RadWindow ID="DisclaimerAlertWindow" runat="server" Width="720px" Height="220px"
Modal="true" visibleStatusbar="false" VisibleTitlebar="false" keepInScreenBounds="true" title="Sourav">
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
In JavaScript, a function is defined for opening the radwindow:-
function openRadWindow()
{
var oWnd = radopen('DisclaimerAlert.aspx, 'DisclaimerAlertWindow');
oWnd.set_title('Access Denied !');
oWnd.Center();
return false;
}
So on the server side of the aspx page, In the Page Load event an IF condition is checked and then I'm calling 'openRadWindow()' function as:-
protected void Page_Load(object sender, EventArgs e)
{
if (fieldValue == "False")
{
string xyz = "<script type='text/javascript' lang='Javascript'>openRadWindow();</script>";
ClientScript.RegisterStartupScript(this.GetType(), "Window", xyz);
}
}
Problem:-
But on running this, these JavaScript errors are coming:-
Object doesn't support this property or method.
'undefined' is null or not an object
Please help how to achieve my objective. I am totally stuck.
Hi I want to share with you my solution to create RadWindow dialog in Javascript code only.
We need to implement 2 methods: one for initializing RadWindow dialog, and the last one for recieving the arguments returned after closing the RadWindow. You can do what you want in this second step (e.x postback,...)
Here is my code:
Initializing RadWindow dialog:
function openMyDialog(url, args) {
var manageWindow = GetRadWindowManager();
if (manageWindow) {
var radWindow = manageWindow.open(url, "<your_dialog_name>");
if (radWindow) {
radWindow.set_initialBehaviors(Telerik.Web.UI.WindowBehaviors.None);
radWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize);
radWindow.setActive(true);
radWindow.SetModal(true);
radWindow.center();
radWindow.set_visibleStatusbar(false);
radWindow.set_keepInScreenBounds(true);
radWindow.set_minWidth(640);
radWindow.set_minHeight(480);
radWindow.setSize(640, 480);
radWindow.set_destroyOnClose(true);
radWindow.add_close(closeMyDialog);//after closing the RadWindow, closeMyDialog will be called
radWindow.argument = args;//you can pass the value from parent page to RadWindow dialog as this line
}
}
}
Closing the RadWindow dialog:
function closeMoveProjectDialog(sender, args) {
var objArgs = args.get_argument();
//objArgs variable stored the values returned from the RadWindow
//you can use it for your purpose
}
How to call this?
You can put the open method into your expected method. In my side, I have a method as shown below and I will call the RadWindow as this way:
function ShowForeignKeyFrontEditSingle(param1, param2){
var url = "ForeignKeyFrontEditSingle.aspx";
var objArgs = new Array();
objArgs[0] = param1;
objArgs[1] = param2;
openMyDialog(url, objArgs);
return;
}
Of course, you have to declare a RadWindowManager control
function GetRadWindowManager() {
return $find("<%=your_radwindow_manager_control.ClientID%>");
}
Take a look here, it explains how to use the ScriptManager.RegisterStartupScript method: http://www.telerik.com/help/aspnet-ajax/window-troubleshooting-javascript-from-server-side.html. Note it the ScriptManager's method. Also look at the Sys.Application.Load event to prevent your code from executing too early.

setting the variable of js function from within htm

I am creating a simple function that warns the user when they are about to close out of a web page. I am using the window.onbeforeonload function is javascript. What I am doing is that, I set a variable to false because of the evil window.onbeforeonload function.
function funky() {
var submitFormOkay = false;
window.onbeforeunload = function () {
if (submitFormOkay == false) {
return "You are about to leave this order form. You will lose any information...";
}
}
}
In my html, this is what I am doing
<input type="submit" id="submit_button" onclick="submitFormOkay = true;">
My question however is that I need a way to fire the function funky().
I know I could use an onclick but if I do what is going to set the value of submitFormOkay.
Any help would be appreciated.
Why not make submitFormOkay a parameter of the function funky, and just call it with the given parameter?
<input type="submit" id="submit_button" onclick="funky(true);">
And in the JS file:
function funky(submitFormOkay) {
window.onbeforeunload = function () {
if (submitFormOkay == false) {
return "You are about to leave this order form. You will lose any information...";
}
}
}
Without changing your HTML, I'd do this instead:
window.onbeforeunload = (function(w) {
w.submitFormOkay = false;
return function() {
if (!w.submitFormOkay) {
return "You are about to leave this order form. You will lose any information...";
}
};
})(window);
​A problem with ngmiceli's solution is that window.onbeforeunload's callback never gets defined until the user is okay to leave the page.

Disable button in update panel on async postback

I have multiple update panels with various asp buttons on a single page. I want to disable the buttons which caused the postback in update panel untill it completes.
Is there a way to avoid using a third party control for this? through JQuery or any other method ?
You can either do this:
cs
//in pageload
//the request is not in postback or async mode
bt1.OnClientClick = "this.disabled = true; " + ClientScript.GetPostBackEventReference(bt1, null) + ";");
Note: you can replace "this.disabled = true" with a js function that will have better handling for disabling the button and maybe display a friendly message as well.
Or this:
http://msdn.microsoft.com/en-us/library/bb383989.aspx
js
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CheckStatus);
function CheckStatus(sender, arg)
{
var postBackElement = arg.get_postBackElement();
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack() && postBackElement.id == "btn1") {
arg.set_cancel(true);
//display friendly message, etc
}
}
Note: I modified it so it checks for the button's id. Replace "btn1"
Good luck!!
You can use the start and stop message of the update panel to disable your controls.
For example
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
document.getElementById("ButtonToDisable").disabled = true;
}
function EndRequest(sender, args) {
document.getElementById("ButtonToDisable").disabled = false;
}
</script>

Categories