How to call a javascript function from asp.net Sub functions? - asp.net

So after extensive search, I found that in order to trigger a javasript function, we could do this:
<script>
function foobar()
{
alert("foobar");
}
</script>
Dim strScript As String = "<script language='javascript' id='myClientScript'>foobar();</script>"
Page.RegisterStartupScript(“callTest”,strScript)
However, the Page.RegisterStartupScript seem to be working only under the Page_load function....
When I put it in a Sub, like this:
Sub Test
Dim strScript As String = "<script language='javascript' id='myClientScript'>foobar();</script>"
Page.RegisterStartupScript(“callTest”,strScript)
End Sub
This won't work. As I link the above function to an asp button. I triggered the button, but nothing happens. So is there anyway to trigger javaScript function conditionally from asp.net? From a Sub function instead of on every page_load?
Thanks!!

You should represent this line
Dim strScript As String = "<script language='javascript' id='myClientScript'>foobar();</script>"
as
Dim strScript As String
strScript = "<script language='javascript' id='myClientScript'>foobar();</script>"
If you want to call javascript for asp.net button click, you can use OnClientClick attribute with a client side function OnClientClick="buttonClick()":-
<asp:button id="Button1"
runat="server"
OnClientClick="buttonClick()"
Text="Click!" />

The javascript injected using the RegisterStartUpscript method is executed when the page is first loaded. Try using the RegisterClientScriptBlock method when you need to inject and execute javascript after the
Type t = this.GetType();
if (!ClientScript.IsClientScriptBlockRegistered(t, "myClientScript"))
{
ClientScript.RegisterClientScriptBlock(t,"myClientScript", sb.ToString());
}
Not sure if it will work inside an updatepanel though

Below is the JavaScript function I am using and have used on numerous web applications where I work. On this specific example, I am comparing the clients IP address to a predetermined IP address on our network, and if the clients IP doesn't match, I display a message box that then informs the user that their specific computer terminal is not permitted to make these specific requests.
Dim ipAdd as string = nothing
ipAdd = Request.ServerVariables.Item("REMOTE_ADDR")
If ipAdd <> "###.###.###.###" then
ClientScript.RegisterClientScriptBlock(Page.GetType, "Script", "<script language='javascript'>alert('This terminal is not permitted to submit requests.');</script>")
End If

Related

Access winform variable from browsercontrol

I have an application in ASP.Net Ajax. I want to open it via a browsercontrol from a winform, and I wish to access a variable (username) that the user used to log in to the webform with. On load I would like to read that username and perform the rest of my webpage code on that browsercontrol using that username.
My ASP.Net Ajax has been published to a internal web server and the browsercontrol loads that IP address.
Is there any way to achieve this at all?
EDIT:
I have discovered the javascript extension: window.external
And I can call a C# procedure from the webpage using javascript with it, which is a start, but I need to retrieve a varaible from c# - this is where the problem comes in. I have tried the
var name = function window.external.GetGlobalVariable(MyGlobalProcedure, "Cannot Get Value");
But javascript error says the method cannot be applied to the object.
Your answer should be as follows:
Public Class Form1
Dim GlobalVar As String = "Your Name"
Dim YourBrowser As New WebBrowser
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
YourBrowser.Url = New Uri("Your URL address")
AddHandler YourBrowser.DocumentCompleted, AddressOf PageLoadComplete
End Sub
'The invokescript will only work once the HTML has finished loading itself into your WebBrowser
Sub PageLoadComplete()
'Must declare the string inside an array as the invokescript only allows an object to be sent
Dim VarToSend As String() = {GlobalVar}
YourBrowser.Document.InvokeScript("yourJavascriptfunction", VarToSend)
End Sub
The javascript section should look as follows:
<script type="text/javascript" language="javascript">
function userNameSet(name) {
$(document).ready(function() {
//variable now exists inside your WebBrowser client and can be used accordingly now
alert(name);
});
}
</script>
References for answer: http://www.dotnetcurry.com/showarticle.aspx?ID=194
"Store that name in a session variable and access the session in your ajax call"
In your ASP.Net application create a hidden field (or if it's somewhere on the UI in some control that works also). Put the username or whatever information you want to share into that field.
From your WinForms program you can request that field through the WebBrowser control like this:
MessageBox.Show(WebBrowser1.Document.GetElementById("txtUsername").GetAttribute("value"))
The above assumes you have some HTML element called txtUsername with the value attribute set.

Loading usercontrol to string and submitting the form within

What i'm doing is creating a website where the design is done i html files that are then read into the masterpage using System.IO.StreamReader.
and inside the html templates there are keywords like #USER.LOGIN#
that I replace with functions etc.
The issue is that i'm replacing #USER.LOGIN# With a usercontrol where there is a login form.
I have a function that reads the usercontrol into a string and it works.
but since the usercontrol is loaded to string alle the events are not following.
so when I submit the login form nothing nothing happends (the page posts) but cannot get any of the fields from the form...
NOTE:
i'm using url-rewriting so urls are http://www.domain.com/account/login
where account is account.aspx and login is the mode the account is in.
Code for replacing the keyword in the streamreader loop (pr line)
If InStr(line, "#USER.LOGIN#") Then
line = line.Replace("#USER.LOGIN#", vbCrLf & userfunc.GetMyUserControlHtml("uc", "account_login.ascx", "/account/login/") & vbCrLf)
End If
And the functions to read usercontrol
Public Shared Function GetMyUserControlHtml(contextKey As String, controllerfile As String, Optional ByVal formaction As String = "")
Dim myId As Guid = New Guid()
Return userfunc.RenderUserControl("~\Controllers\" & controllerfile, "", myId, formaction)
End Function
Public Shared Function RenderUserControl2(path As String, Optional ByVal formaction As String = "") As String
Using pageHolder As New Page(), _
viewControl As UserControl = DirectCast(pageHolder.LoadControl(path), UserControl), _
output As New StringWriter(), _
tempForm As New HtmlForm()
If formaction <> "" Then
tempForm.Action = formaction
Else
tempForm.Action = HttpContext.Current.Request.RawUrl
End If
tempForm.Controls.Add(viewControl)
pageHolder.Controls.Add(tempForm)
HttpContext.Current.Server.Execute(pageHolder, output, False)
Dim outputToReturn As String = output.ToString()
Return outputToReturn
End Using
End Function
How would you guyz do this?
I need the userlogin to be hardcoded in the usercontrol but still be able to place it anywhere using the template keyword.
This will also be used with other functions (newsletter signup, shoutbox etc.)
what i would suggest is register you control on the web config..
<add tagPrefix="CustomControl" tagName="LogIn" src="~/UserControls/Login.ascx"/>
you can still use "#USER.LOGIN#" but instead of replacing it with a control...
replace it with a something like this
<CustomControl:LogIn id="LogIn" runat="server"/>
this is just a quick write up.. but you could always try if it works
you can save your HTML like this istead of placing an actual "#USER.LOGIN#"
<% =GetLoginControl() %>
and then create a public function in your code behind named GetLoginControl() and return a response.write of the HTML Mark up you need

CustomValidator not working

I have a CustomValidator that checks if text entered in textboxes matches certain fields in a database. This was all working great before, but I have modified my page quite a bit since then and it is no longer working. I didn't think I changed anything that would affect this, but apparently I did. All my other validators (required field validators) are working correctly, but my CustomValidator isn't responding.
So anyway, here is my code:
CustomValidator:
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtCoursePrefix" ErrorMessage="Course number is already taken."></asp:CustomValidator>
VB codebehind:
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
'Checking for duplicate course numbers
'get values
Dim checkPrefix = txtCoursePrefix.Text
Dim checkNum = txtCourseNum.Text
'db connectivity
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource2.ConnectionString
myConn.Open()
'select records
Dim mySelect As New OleDbCommand("SELECT 1 FROM tableCourse WHERE prefix=? AND course_number=?", myConn)
mySelect.Parameters.AddWithValue("#checkPrefix", checkPrefix)
mySelect.Parameters.AddWithValue("#checkNum", checkNum)
'execute(Command)
Dim myValue = mySelect.ExecuteScalar()
'check if record exists
If myValue IsNot Nothing Then
CustomValidator1.SetFocusOnError = True
args.IsValid = False
End If
End Sub
Everything is working up until CustomValidator1.SetFocusOnError = True and args.IsValid = False. I have tested the If statement and it's working correctly, it returns true and anything else I put inside of it executes.
Things you should know when using customvalidators:
If you are validating using a ValidationGroup, don't forget to add it to your CustomValidator.
Set the ControlToValidate property.
A CustomValidator control never fires when the ControlToValidate control is empty unless you set ValidateEmptyText=true.
When using ClientValidationFunction="customClientValidationFunction" use the following signature:
function customClientValidationFunction(sender, arguments) {
arguments.IsValid = true; //validation goes here
}
You should set the property ValidateEmptyText="true" on the CustomValidator. The client and server functions will always be called in that case.
It solved the problem for me.
If the handler is getting called, and you're successfully setting the args.IsValid to false, then what that does is it sets Page.IsValid to false. But unfortunately, that doesn't stop the form from being sumbitted. What you need to do is check that Page.IsValid property in your code that handles your form submit, like in the submit button handler.
So in addition to the code you posted, which sounds like it is working correctly, make sure that you have something like this for your submit handler (C# example):
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
// by simply returning, the error message for the CustomValidator will be displayed
return;
}
// do processing for valid form here
}
Use this
OnServerValidate="CustomValidator1_ServerValidate"
like an example and it will work....
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtCoursePrefix" ErrorMessage="Course number is already taken." OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
Gaurav Agrawal
First of all, put validation group on validators and the button. If that too doesnt work, put OnClientClick='CheckValidate();' and declare the function which will call page_clientvalidate method along with the parameter.. validation group. This would surely work. If that is not working put debugger in the javascript method and debug the same

call a vb.net subrouting from a javascript function?

hi folks i have a subroutine called CheckDate() in the code behind.
How would I call that subroutine from a javascript function?
Cheers,
-Jonesy
You can't call it directly as function call.
because Javascript is a scripting langauge aimed for web browsers.
you may use AJAX or full page post sending the parameters to allow you to execute the subroutine.
Read more about Ajax it is the better way to go.
To expand on what Kronass said there I've found this article to be useful in the past for doing what you want http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/. Encosia also has a heap of other blog plots on this if you do a bit of searching
What you're looking to use is normally called a WebMethod, ScriptMethod or Page Method depending on which framework you're using
One way to do this is by using the ICallbackEventHandler interface. I saw you had a question regarding the AjaxControToolkit CalendarExtender the other day so I'm guessing this question is in relation to that and how you do some validation in a server-side method. ICallbackEventHandler is AJAX, but you can write your validation as a normal method, not a PageMethod/WebMethod. It's slightly more fiddly on the Javascript side, but not by much.
Let's start with our basic textbox and calendar extender:
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager" />
<div>
<asp:TextBox runat="server" ID="DateTextBox" />
<ajaxtoolkit:CalendarExtender runat="server" ID="CalendarExtender" TargetControlID="DateTextBox"
PopupButtonID="SelectorButton" OnClientDateSelectionChanged="checkDate" Format="dd MMM yyyy" />
<asp:ImageButton runat="server" ID="SelectorButton" ImageUrl="Path to a pretty graphic" />
<br />
<asp:Label runat="server" ID="ValidDateLabel" />
</div>
</form>
I've added the OnDateSelectionChanged attribute of the extender as this will kick off the process of calling the server-side method; we'll come back to what goes in there shortly.
In the class declaration in your code-behind, you need to say that you are implementing the interface:
Partial Public Class _Default
Inherits System.Web.UI.Page
Implements ICallbackEventHandler
To implement the interface we then need to add two more methods to handle the two methods in the interface, RaiseCallbackEvent and GetCallbackResult. We also need a property for a bit of temporary storage of the date we are trying to validate.
Private mCallbackDate As Date
Private Property CallbackDate() As Date
Get
Return mCallbackDate
End Get
Set(ByVal value As Date)
mCallbackDate = value
End Set
End Property
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements ICallbackEventHandler.RaiseCallbackEvent
'eventArgument will contain the date the user selected from the extender
Dim testDate As Date
If eventArgument = String.Empty Then
Else
If Date.TryParse(eventArgument, testDate) Then
'If we have a legal date selected then store it
Me.CallbackDate = testDate
End If
End If
End Sub
Public Function GetCallbackResult() As String Implements ICallbackEventHandler.GetCallbackResult
Dim result As String = String.Empty
'Get the date that we stored in memory and pass it to our CheckDate function
'We'll pass back to the Javascript in the page the string 'true' if the date is
'valid under our business rules and 'false' if it isn't
If checkDate(Me.CallbackDate) Then
Return "true"
Else
Return "false"
End If
End Function
Public Function checkDate(ByVal dateToCheck As Date) As Boolean
'If the date is in the future then return True, otherwise False
If dateToCheck > Date.Today Then
Return True
Else
Return False
End If
End Function
There's one more bit of server-side we need to add, in Page_Load, which does the hooking up of the Javascript and server-side code. The ClientScriptManager's GetCallbackEventReference function will inject a bit of script into our page that takes care of the communication between browser and server. Then we just need to register a script block that calls the injected script - we'll call this function checkDateOnServer.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim callbackScript As String
callbackScript = "function checkDateOnServer(arg){" & _
Page.ClientScript.GetCallbackEventReference(Me, "arg", "receiveDateValidation", "") & _
"}"
ClientScript.RegisterClientScriptBlock(Me.GetType, "callback", callbackScript, True)
End Sub
Back to the client-side bits. We need to write a Javascript checkDate function that'll pass the user's selected date into the callback.
function checkDate()
{
// Get the date the user selected
var selectedDate = document.getElementById('DateTextBox').value;
// This will start the callback sequence
checkDateOnServer(selectedDate);
}
The last bit we need to do is receive the value coming back from the server, which we said in Page_Load would be called receiveDateValidation.
function receiveDateValidation(arg, context)
{
var ValidDateLabel = document.getElementById('SelectedDateLabel');
// We get a string value back from the server which is 'true' or 'false'
if (arg == 'true')
{
ValidDateLabel.innerText = 'Your date IS valid';
}
else
{
ValidDateLabel.innerText = 'Your date IS NOT valid';
}
}

How do I call javascript just before a response redirect

I'm trying to run some java script just before a page redirect but it fails to run.
When I comment out the Response.Redirect all works fine but this goes against the particular requirements. Any ideas on how to implement this functionality?
Dim strscript As String = "<script>alert('hello');</script>"
If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If
Response.Redirect("http://www.google.com")
Your problem is that the Response.Redirect redirects the response (...) before anything is sent back to the client. So what the client gets is a response from Google rather than from your server.
In order to write some javascript on the page and have it execute before sending the client to Google, you'll need to do your redirect in javascript after the alert.
Dim strscript As String = "<script>alert('hello');window.location.href='http://www.google.com'</script>"
If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If
The client isn't getting a chance to load. Try redirecting from the client side:
Dim strscript As String = "<script>alert('hello');window.location.href("http://www.google.com");</script>"
If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If
If you want to execute some javascript before redirecting, you will need to do the redirect in javascript and not in ASP.NET.
Dim strscript As String = "<script>alert('hello'); window.location.href='http://www.google.com';</script>"
If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If
Not Working:
string sScript = "<script language='javascript'>alert(\"" + Alertstr + "\"); alert('Record has been Updated Successfully'); </script>";
ClientScript.RegisterStartupScript(typeof(Page), "alert", sScript);
response.redirect("LandingPage.aspx");
Working:
string sScript = "<script language='javascript'>alert(\"" + Alertstr + "\"); alert('Record has been Updated Successfully'); window.location.href = 'LandingPage.aspx'; </script>";
ClientScript.RegisterStartupScript(typeof(Page), "alert", sScript);
If you use a Response.Redirect it actually sends a 3XX response to the browser which causes it to send a request to the URL in the redirect. It won't actually load/render any data contained with the response (actually I don't think any data is sent). If you want it to redirect after the page loads, you may want to either include a META refresh header that redirects a certain amount of time after load or use javascript do to the redirect at the end of your script.

Resources