Script never seems to register - asp.net

I have the following simple test asp.net form, with following vb.net load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strScript As String
strScript = "function MyMsg()"
strScript += "{"
strScript += "alert(document.getElementById('TextBox3').value);"
strScript += "}"
ClientScript.RegisterStartupScript(Me.GetType(), "MyMsg", strScript, True)
End Sub
It simply displays the contexts of a text box in the web page when the script is called.
I then have this button code:
Protected Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
If ClientScript.IsStartupScriptRegistered("MyCall") Then
Me.TextBox3.Text = "My text - registered"
Else
Me.TextBox3.Text = "my text NOT registered"
End If
ClientScript.RegisterStartupScript(Me.GetType(), "MyCall", "MyMsg();", True)
End Sub
However, the button when clicked on always shows the text NOT registered. So, the code seems to run ok. It grabs the text from the text box no problme. However, the True part of the code never runs.
Is this a state or scope issue? (or the the fact that the code is only injected one time) that prevents this from running the code block for true?
How can I get the "true" part of the above code to run?

Consolidating(and elaborating on) the comments on the original question here.
The issue is that ASP.NET buttons cause full post backs to the server everytime they are clicked and when a page does a full postback it resets all scripts that may have been registered from previous actions. This means that any script that was registered the last time the button was clicked will be wiped out and the page will not know anything about it the second time around.
There are a few ways to get around this.
UpdatePanel: My prefered way is to declare all your controls that need to be manipulated in the button click handler inside an AJAX Update Panel like:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" />
</ContentTemplate>
</asp:UpdatePanel>
What this does is limits what the button can change when it is clicked and causes a post back. In order to use this you will also need to declare a Scriptmanager anywhere before the updatepanel. When you register the script you will need to use that scriptmanagers RegisterScriptControl function.
Manual AJAX Postback: Another way to accomplish this would be to use a "manual" AJAX call. I've done this a few times but it is much more complex than the update panel version and I'm not sure if the way that I've done it is the "right" way to go about it. First you will change you ASP button to a regular HTML input button. On the HTML button the onclick should be a javasciprt function that you designate. Inside the javascript function you will need to go through the process of declaring an XMLHttpRequst object. This site goes over how to use the object pretty thoroughly. The way that I have gotten information back and forth is by using the headers attached to the request/response. You need to add them using setRequestHeader function and get them from the getAllResponseHeaders function. Once you get into the page load event on the server side you will need to evaluate the headers of the request and if one exists that signifies that the button was clicked(which you will need to add manually) then you can call a function and add a header to the response that will tell the javascript what to display in the pop up box. I'm sure using headers isn't the best method for getting inormation back and forth but if you are just talking about booleans that only dictate what to print to the user then you probably don't need to go through the process of setting up a JSON or XML response. This is also assuming that you are doing more on the server side than just checking how many times the button has been clicked because if thats all you need to do you should use option 3.
The simplest way to accomplish this would be to make the entire thing a javascript function. Declare a variable(int) on the page and set it to 0 on load. Then when the button is clicked you would just need to check the counter, if its greater than 0 display one message, if its 0 then display a different message. This will only work if your condition is very basic(it can get very complex but sometimes thats overkill).
So, In my opinion, those three options should be able to handle whatever you need to do. The first is very simple to use, the second is very versatile and can become very powerful if you implement XML or JSON in your communications with the server and the third is much faster than communicating with the server every time. Deciding which will be the best fit is up to you.

You did not add the script tag to enclose your script.
Adding function
strScript = "<script type=\"text/javascript\">";
strScript = "function MyMsg()"
strScript += "{"
strScript += "alert(document.getElementById('TextBox3').value);"
strScript += "}"
strScript = "</script>";
ClientScript.RegisterStartupScript(Me.GetType(), "MyMsg", strScript, True)
Calling function
ClientScript.RegisterStartupScript(Me.GetType(), "MyCall", "<script type=\"text/javascript\">MyMsg();</script>", True)

Related

ScriptManager.RegisterStartupScript not working if Response.redirect used

In my page load based on certain condition i call UserMsgBox("user Not Authorize") and it is working. while if i call Response.Redirect("Home.aspx") after that it is not showing alert message.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Request.QueryString("val") IsNot Nothing Then
...
Else
UserMsgBox("user Not Authorize")
Response.Redirect("Home.aspx")
End If
End Sub
Private Sub UserMsgBox(sMsg As String)
Dim jScript As String = "alert('" + sMsg + "');"
ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "onclick", jScript, True)
End Sub
i want alert message to be popup and Response.Redirect("Home.aspx") also work. any would be appreciated .
You have to set some kind of session() value and get/grab/see this on the home.aspx page.
The problem is at "this instant" you are on the current page. When you run that userMsgbox code, it is injected into the CURRENT page. Unless that page makes a full round trip
eg:
User hits some button on web page.
Web page travels up to web server.
Code behind runs - maybe you modify some controls.
And THEN you as the last thing, inject the userMsgbox.
Now the page travels back down to client side.
The browser side then renders the page.
After it renders, then your injected js runs.
But, you NEVER let that page make it back to the client side, you have this:
Response.Redirect("Home.aspx")
So we never let the page travel back - we chop it off and say load another page.
But our current code context is the currently loaded page. Not the one you jumping to.
So, your current page-behind code is working on the current page - and controls you change/set/modify or script you inject is going to operate on that current loaded page.
With the re-direct then that page never makes the trip down to the client side - you sending to a NEW page home.aspx
Two ideas:
Use/set some kind of session().
Say like
Session("HomeMessage") = "user Not Authorize"
Response.Redirect("Home.aspx")
Then in the home.aspx page (load event), you need:
if isPostBack = false then
if Session("HomeMessage") <> "" then
Call UserMsgbox(Session("HomeMessage")
Session("HomeMessage") = ""
end if
end if
So now when the full home page renders browser side, then your msgbox you injected will also run. That might not be the best UI.
But with that setup (the re-direct occurring server side), then you can't do this on the previous page (well, actually our current page). But that page never travels back to the client side - you re-direct to home page, and that what gets send down to the browser.
(so you need that userMsgbox sub in the home.aspx page). I mean, if you set some text box on that page - we never see that either - since the code jumps to load a fresh new (different page) that the code behind is running against.
And this does mean that the home page will display FIRST and then the msgbox will show.
The other way?
Well, you could allow the current page to post back, and have the js script display the message AND ALSO do the jump to the other page.
This would thus allow the current page to display with the msgbox. You then hit ok, and the client side does the jump to home. (you remove your response.redirect.
So you could replace this:
UserMsgBox("user Not Authorize")
Response.Redirect("Home.aspx")
With say a routine like this:
UserMsgBoxJump("user Not Authorize","Home.aspx")
and
Private Sub UserMsgBox2(sMsg As String, strURL As String)
Dim jScript As String = "alert('" + sMsg + "');window.location.href = '" & strURL & "';"
ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "onclick", jScript, True)
End Sub
So now, we let the page travel back (it will render), and after full page render, then your injected js can run. Then the msgbox will display.
And when the user hits ok, then the client side js code does the navigation to the target page.
So, it really depends on how you want to do this. Probably the 2nd idea is more flexible, since then you don't have to mess up the home page on-load event to check the session.
So keep the post/page life cycle in mind.

Move Focus to Server Side Validator

I have a page with multiple CustomValidators and I want the focus to be brought to the offending validator when there is an error. I know this is possible with client side validation, but is it possible with server side?
Additionally, the CustomValidators are located in different parts of the page so I can't simply scroll the page to one general location when there is any validation failure.
I have tried:
SetFocusOnError
CustomValidator.Focus() immediately after validation, after the button click, and in Page.PreRender()
Thanks in advance
Thanks to a colleague, I have a solution to this question. It's so simple I wish I had come up with it! Just inject javascript when the validator fails and that javascript will be executed on postback.
Private Sub CustomValidator_ServerValidate(ByVal source as Object, ByVal args as System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator.ServerValidate
If someCondition Then
args.IsValid = True
Else
args.IsValid = False
System.Web.UI.ScriptManager.RegisterStartupScript(Me, Me.GetType(), "JumpToValidator", "jumpToValidator(validatorId);", True)
End If
End Sub`
where jumpToValidator(validatorId) is a javascript function that scrolls to the element passed in as an argument.

asp.net imagebutton firing on Enter key

I researched this problem here on SO and tried the apparent solution which did not work, so here it is:
I have a very complex form with among other controls, three autocompleting textboxes.
I also have a client who cannot seem to stop entering a value in the textboxes and hitting the Enter key to select the desired value from the autocomplete list.
When they hit Enter, the first imagebutton in the form fires, doing something completely different. So to them, the form is broken.
What I need to do is to prevent the Enter key from firing these imagebuttons (there are 10 of them in the form).
I have tried the following code in both Page_Load and Page_LoadComplete, neither of which work:
imgbtn1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")
Any advice that saves me a few hairs is appreciated.
One good solution can be found here:
Disable Button click, ImageButton click and/or form submit on Enter Keypress
Adding Markup from Link
<form id="form1" runat="server">
<input type="submit" style="position:absolute;left:-100px;top:-100px;width:0px;height:0px;" onclick="javascript:return false;" />
<!-- other form controls below this line -->
</form>
Did you check these two references
http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
http://www.webcheatsheet.com/javascript/disable_enter_key.php
They are essentially doing the same thing you are trying, just that they are hooking it up to a different event. Also make sure that your Javascript is foolproof i.e. if javascript has some errors, then your end result may not be as expected.
The second link Subhash Dike posted (Disable Enter Key) worked for me. I have two ImageButtons and they both don't fire a postback when using this function (bit modified from the original) which is great.
document.onkeypress = function (evt) {
return ((evt) ? evt : ((event) ? event : null)).keyCode != 13;
};
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Page.Form.DefaultButton = BtSearch.UniqueID
If Not IsPostBack Then
' ...............
End If
End Sub
I had a similar problem.
Listview1.ImageButton was responding to ENTER.
We really want a SAVE to happen (or nothing, but the bad behaviour was reloading the page and that made them grumpy)
Set up a handler for the window to catch events. I do this in docReady()
function docReady() {
$(document).keydown(mapKeyCode);
};
In that handler, find the keycode you want to capture ( enter is 13)
https://css-tricks.com/snippets/javascript/javascript-keycodes/
function mapKeyCode(event) {
{
if (event.keyCode == 13) {
//event.stopPropagation();
//event.preventDefault();
__doPostBack('ctl00$cp1$InventoryPieces$btnSubmit', '');
}
}
event.StopPropogation will cause nothing to happen.The keystroke is simply eaten. That may be what you want. You are still free to call an ajax method below, that's not part of the event.
event.PreventDefault is supposed to stop the event from doing what it normally does. I had troubles seeing a difference w/ this line commented out or not. There is in depth discussion on preventDefault and ENTER here on SO.
This 3rd line is what the people who pay me want to have happen when they hit the ENTER key even though they probably should be hitting tab. I tried (#).trigger() and didn't have a lot of luck. Inspecting the element, I saw that it was calling __postback, so I pasted that in. I'm reasonably certain ().Trigger would work if i figured out what i was doing wrong, I just took another route.
This is hackish to me, but it accomplishes the objective.
Hope it helps.

what is keyword If Page.IsPostBack how can use it

What is this keyword how can use it?
If Page.IsPostBack = False Then
IsPostBack
Here is an overview of IsPostBack from MSDN:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
It quotes:
true if the page is being loaded in
response to a client postback;
otherwise, false.
The postback is useful, say for example you have a Literal control on the page, and the code on page load sets the Literal.text += "hello"; If you have a button on that page, and press it, the text of the literal will get longer and longer, hellohellowhello, if you wrap the code in (c# example):
if(!Page.IsPostBack){
Literal.text += "hello";
}
The Literal text now wont expand when the button is pressed.
Other Notes
Instead of:
If(Page.IsPostBack = False)
Do:
If(!Page.IsPostBack)
This is logically the same and is generally accepted to be a better way of writing the statement.
Also you marked the question C#, but the If syntax you used indicates you are writing it in VB.net, not C#.
Gets a value indicating whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.
Return Values:
true if the page is being loaded in response to a client postback; otherwise, false.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
The IsPostBack tells you whether or not the page has been Posted Back, meaning "server side" button has been clicked.
You can "use" it by reading its value and acting upon it.
It's useful for example when you add controls dynamically to your page, so you don't have to add them when it's a PostBack.
Official documentation already been posted by others, look there for any further or technical details.

How to wait three seconds then turn to another webpage

I'm new to web development, and I'm currently using ASP.net. I wonder what would I need to do to let the browser wait for 3 seconds so my users can read the text "Customer Successfully Added" before turning to another page? I have attached my code as follows.
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim db As New DatabaseClass
db.addProfile(txtLN.Text, txtFN.Text, txtUsername.Text, txtPassword.Text, txtAddress.Text, txtZip.Text, txtPhone.Text, txtEmail.Text)
lblMessage.Text = "Customer Successfully Added"
End Sub
In addition, I'm not sure how to utilize MSDN. For me, its information overload, I'm wondering how to go about finding the solution on MSDN so i would be able to solve my problems in the future. Thank you!
You can't do it in the code behind of the page because of how asp.net works - the label text would not update until after the timeout occurred if you did it in the code-behind.
The server-side processing spits all the html back to the browser only after it has completely processed any server-side code unless you're using Ajax. Since you're new, I won't even bother going into how to do it with Ajax as there is a MUCH simpler option for accomplishing what you want.
A simple method to accomplish what you're looking for would be to have a simple HTML page that just has a message that says "Customer successfully added" and use javascript (client-side code) to pause and then redirect using the Javascript "SetTimeout" function.
There's an example here: http://www.bloggingdeveloper.com/post/JavaScript-Url-Redirect-with-Delay.aspx
The logic flow wshould work like this:
The original page should add the record (in code-behind) then redirect to this simple html page (in code-behind). The html page should have the "Customer Added" message and use the SetTimeout and Redirect to go to whatever page you want the user to see after viewing the message.
For stuff like this you need the code to run client side rather than on the server. The easiest way to do this is to return some javascript with your page (in the .aspx part rather than the code behind)
Take a look here for an idea of what to do :)
The page is displayed for a few seconds and then the javascript triggers a redirect to a url of your choosing. Just add something like this into your html.
You can emit javascript to redirect to the other page, using the setTimeout function.
This is best accomplished using the ScriptManager to register any javascript on the page.

Resources