RegisterStartupScript error message VB.NET - javascript

I am trying to call JavaScript code from my VB.NET code behind and use the following code:
Protected Sub ApplyGridViewPageChangingActions(ByVal sender As Object, ByVal e As EventArgs) Handles GridView_Body.PageIndexChanged
Dim oldPageIndex As Integer = Context.Session("GridViewPage")
If GridView_Body.PageIndex > oldPageIndex Then
Dim func As String = "ApplyGridViewPageChangingActions('" + Context.Session("LastFundCode") + "', '" + Context.Session("ExpOrColl") + "');"
Context.Session("GridViewPage") = GridView_Body.PageIndex
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ApplyGridViewPageChangingActions", func, False)
End If
End Sub
However I am getting this error message:
JavaScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: The script tag registered for type 'ASP.lsc_code_placeorders_aspx' and key 'ApplyGridViewPageChangingActions' has invalid characters outside of the script tags: ApplyGridViewPageChangingActions('baef', '0');. Only properly formatted script tags can be registered.
Why is it not properly formatted? ApplyGridViewPageChangingActions('baef', '0'); looks perfectly acceptable to me.

Related

Output a string from code behind to a new page or window

Assume a string variable in code behind containing some HTML content such as
Dim str1 As String = "<h3>hello</h3><p>some paragraph</p><table><tr><td>some table content</td></tr></table>"
A saved file could be opened by registering a script such as
Dim script1 As String = "window.open('popupPage.html', 'myPopup')"
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "someId", script1, true)
Is there any way to output this content in a new tab or window from code behind without saving it to a file?
You can pass an empty string for a file name
'Declare a script with your variable
Dim script1 As String = "<script>var popwin = window.open('','myPopup');popwin.document.write('" & str1 & "');</script>"
'Call your script with ScriptManager for async postback from UpdatePanel
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "poptest", script1, true)
'Call your script with ClientScript for synchronous postback outside/without UpdatePanel
ClientScript.RegisterStartupScript(Me.GetType, "popuptest", script1, True)
check this Call javascript function from asp.net code behind after server side code executes

Open an asp.net Page inside of an iframe

In my web site I have two pages... one is the Assistance.aspx, and the other is Help01.aspx
What I want to do is to open the second page inside the iFrame which is in a table column this column belongs to a table which is inside of the Assistance.aspx page:
For this purpose I use the following code:
<iframe id="iFrame" runat="server" class="tablecolumndiv" >
And in my code behind I use:
Protected WithEvents iFrame As System.Web.UI.HtmlControls.HtmlGenericControl<br/>
Public frame1 As HtmlControl = CType(Me.FindControl("iFrame"), HtmlControl)
But when I come to the:
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
frame1.Attributes("src") = "/Pages/Support/Asp/Help01.aspx"
End Sub
It throws me an error of :
Object reference not set to an instance of an object.
Because the Me.FindControl("iFrame") has value of nothing
That error eliminated when I delete the runat from the element.
Why?
* ADDITIONAL INFORMATION *
I also use the following script for the same reason:
<script type="text/javascript">
function setPage(frame, pName) {
document.getElementById(frame).src = pName;
}
</script>
Which I call it from my code behind:
Private Sub button1_Click(sender As Object, e As System.EventArgs) Handles button1.Click
Dim myNewAsp As New AspNetSqlProvider
myNewAsp.InitializeSite(sender, e)
Dim url As String = "/Pages/Support/Asp/Help01.aspx"
Dim urlURI As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim urlPath As String = HttpContext.Current.Request.Url.AbsolutePath
Dim myServerName As String = Strings.Left(urlURI, urlURI.Length - urlPath.Length)
root_url = myServerName
Dim assist As New Assistance
Dim frameName As String = "iFrame" 'assistiFrame.ID
iPageLoad(frameName, sender, root_url + url)
End Sub
Public Sub iPageLoad(FrameId As String, sender As Object, msg As String)
Dim cstype As Type = Me.GetType()
Dim innerMess As String = msg
Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim script As String = "setPage('" + FrameId + "', '" + innerMess + "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "iPage") Then
Page.ClientScript.RegisterStartupScript(cstype, "iPage", script, True)
End If
End Sub
That script also throws me the same error.
Finally we’ve seen that this issue have two solutions, every one of those two solutions have it’s own results.
The first solution is to declare the iFrame like this:
Protected WithEvents iFrame As System.Web.UI.HtmlControls.HtmlGenericControl
And in the Button_Click handler we use the:
iFrame.Attributes("src") = "/Pages/Support/Asp/Help01.aspx"
And in the design view area we use the:
<iframe id="iFrame" runat="server" class="tablecolumndiv" >
This solution works fine, and produces an excellent result.
Of course we have another solution described in the ADDITIONAL INFORMATION but that one needs to delete the runat=”server” from the declaration in the design view area.
Choose and Pick….

Javascript fired from ASP.net codebehind runs in Chrome but not in IE9

I have a strange issue with a small bit of code, which runs fine in Chrome but wont fire in IE9.
I have a sub:
Private Sub MessageBox(ByVal msg As String)
Response.Write("<script language='javascript'>window.alert('" + msg + "'); window.history.back(1); return false;</script>")
End Sub
Which is called in the Page_Load event if the page is marked as unpublished in the database.
This works fine in Chrome, but not at all in IE (and yes i have checked JS is enabled!)
Or you may write the JavaScript code in a new line or as a new JavaScript function:
Private Sub MessageBox(ByVal msg As String)
Response.Write("<script language='javascript'>")
Response.Write("window.alert('" + msg + "'); window.history.back(1); return false;")
Response.Write("</script>")
End Sub
So that the JavaScript code is written in a new line separate from the markup.
Or you may try to use RegisterStartupScript if you're using ASP.Net
Please use this answer as a starting point and not as a copy-paste solution.

Web method wont call, but does not error

Im struggling to get a web method to work in VB. The javascript gets called but never seems to call the web method. I am running in debug mode and get no errors.
Here is the code:
<System.Web.Services.WebMethod()>
Public Shared Sub PasteEvent(EventID As Integer,
startDate As DateTime,
endDate as DateTime,
newStart As DateTime)
' work out the diff between start and end
Dim difference As long = DateDiff(DateInterval.Minute,startDate,endDate)
' pasteStart + minutes from the event start
' this is because we can only paste on the hour, but events may have started after the hour
' ie 10:15
newStart.AddMinutes(startDate.Minute)
' new end = pastestart + diff
Dim newEnd As DateTime = newStart.AddMinutes(convert.ToDouble(difference))
' call database
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Blueprint").ToString())
Dim cmd As New SqlCommand
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spOPSCopyEvent"
cmd.Parameters.AddWithValue("#EventID", EventID)
cmd.Parameters.AddWithValue("#StartDate", newStart)
cmd.Parameters.AddWithValue("#EndDate", newEnd)
cmd.Connection = conn
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End sub
The javascript that calls it:
<script type="text/javascript" language="javascript">
function eventCopy(eventID, start, end)
{
alert("copy");
// grab the event id and store it in a hidden text box
$("#ctl00_MainContent_hidCopyEventID").val(eventID);
$("#ctl00_MainContent_hidCopyStart").val(start);
$("#ctl00_MainContent_hidCopyEnd").val(end);
}
function eventPaste(eventStart)
{
alert("paste");
alert(eventStart);
// Call a web method, passing the eventID and the new start time
var eventID = $("#ctl00_MainContent_hidCopyEventID").val;
var startDate = $("#ctl00_MainContent_hidCopyStart").val;
var endDate = $("#ctl00_MainContent_hidCopyEnd").val;
PageMethods.PasteEvent(eventID, startDate, endDate, eventstart)
}
</script>
So far I have :
Updated my script manager in the master page to have enablePageMethods="true"
Tried adding Imports System.Web.Services
Moved the javascript into the body rather than the head
The problem is that you are missing exception handling mechanism to
see what error did you get .
Put try and catch in javascript and vb code and print the error.
Use the sniffer like Fidler to see what you are sending .
Try to print trace messages in web services using
Trace.Log and you can see them after running DebugView and see where you are falling
When using this line:
var eventID = $("#ctl00_MainContent_hidCopyEventID").val;
I should have put:
var eventID = $("#ctl00_MainContent_hidCopyEventID").val();
Accepting Gregorys answer as fiddler was the most helpfull in diagnosing the issue.

Best/efficient way to include JavaScript when using User Controls

I'm to .NET and all the associated cool stuff you can do, but am wondering about efficiency with User Controls and JS includes.
My user controls are mainly made up with an ascx display page and .vb.ascx code behind, as is customary with the code-behind coding style of .NET, which is great for coding simplicity although it does double then bear of files required. However, as I understand it, the server compiles these and returns the HTML efficiently.
Where the Control requires JavaScript, as I'm developing, I am making external JS files for each User Control with the same name, so the user controls consist of 'controlName.ascx, controlName.vb.ascx, controlName.js'
If a page requested by the user contains several User Controls the browser will be requesting multiple JS files, probably a master page JS file, jQuery AND each required file for the respective Controls.
This approach makes sense to me whilst developing and as everything's all kept nice and neat, making problem solving easy, but when it goes live there'll be loads of get requests from the browser, given that each time the browser gets a file, even the process of requesting the file to check if its cached or not must take some time.
Would I be best off including my JS inline in the ascx files, or code behind, directly inserting the script, or what is the 'correct' way to handle these multiple files to reduce get requests from the browser.
I'm using CSS sprites for buttons and stuff for the same reason, so wondering what to do with JS files. In my case CSS is generally handled by classes in the primary pages, so these are not an issue.
We actually built a control on top of ScriptManager that automatically extracts all of the js from all controls on a page, including scriptresource.axd and stores them in a single cached file. This has greatly improved performance and reduced maintenance work since it is automated. We built this starting in .Net 2.0, so I am not sure if ScriptManager now provides the same functionality, but I thought it was worth mentioning.
Here is our implementation of this class:
Option Explicit On
Option Strict On
Imports System.Collections.Generic
Imports System.Web.SessionState
Public Class OurScriptManager
Inherits ScriptManager
Implements IRequiresSessionState
Private m_ScriptBuilder As New StringBuilder
'Private m_sSessionIndex As String = ""
Private m_cScripts As List(Of ScriptReference)
Private m_fIsCached As Boolean
Private m_sScriptName As String = ""
Private m_sScriptFileName As String = ""
Const CACHED_SCRIPTS_DIR As String = "/scriptcache/"
Public Sub New()
' default constructor
End Sub
Public Property ScriptName() As String
Get
Return m_sScriptName
End Get
Set(ByVal value As String)
m_sScriptName = value
End Set
End Property
Private ReadOnly Property ScriptFileName() As String
Get
If String.IsNullOrEmpty(m_sScriptFileName) Then
m_sScriptFileName = "~" & CACHED_SCRIPTS_DIR & Me.ScriptName & ".js"
End If
Return m_sScriptFileName
End Get
End Property
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
' Exceptions are handled by the caller
MyBase.OnInit(e)
If String.IsNullOrEmpty(Me.ScriptName) Then
Me.ScriptName = Me.Page.ToString
End If
' this compiled script should be cached on the server
' check for the file, if it exists, load that file instead of generating it
If Configuration.HasPageScriptBeenCached(Me.ScriptFileName) AndAlso File.Exists(Me.Page.Server.MapPath(Me.ScriptFileName)) Then
m_fIsCached = True
Else
m_cScripts = New List(Of ScriptReference)
End If
End Sub
Protected Overrides Sub OnResolveScriptReference(ByVal e As System.Web.UI.ScriptReferenceEventArgs)
Try
MyBase.OnResolveScriptReference(e)
If Not m_fIsCached Then
' First, check to make sure this script should be loaded
Dim fIsFound As Boolean
For Each oXref As ScriptReference In m_cScripts
If oXref.Assembly = e.Script.Assembly AndAlso oXref.Name = e.Script.Name AndAlso oXref.Path = e.Script.Path Then
fIsFound = True
Exit For
End If
Next
' If this script is found within the list of scripts that this page uses, add the script to the scripthandler.aspx js output
If Not fIsFound Then
Dim oReference As ScriptReference
Dim oElement As ScriptReference
Dim fIsPathBased As Boolean
oElement = e.Script
If String.IsNullOrEmpty(oElement.Path) AndAlso Not String.IsNullOrEmpty(oElement.Name) AndAlso String.IsNullOrEmpty(oElement.Assembly) Then
' If resource belongs to System.Web.Extensions.dll, it does not
' provide assembly info that's why hard-coded assembly name is
' written to get it in profiler
oElement.Assembly = "System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
End If
'check to see what type of script this is
If Not String.IsNullOrEmpty(oElement.Path) Then
' this script is a physical file
oReference = New ScriptReference(oElement.Path)
fIsPathBased = True
ElseIf Not String.IsNullOrEmpty(oElement.Assembly) AndAlso Not String.IsNullOrEmpty(oElement.Name) Then
' this script is generated by an assembly
oReference = New ScriptReference(oElement.Name, oElement.Assembly)
Else
' Couldn't find script, so bail to allow standard processing to take place.
Return
End If
If Not fIsPathBased Then
Dim sUrl As String
Dim oRequest As HttpRequest
Dim sScriptResourcePath As String
sUrl = GetUrl(oReference)
sScriptResourcePath = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}", Context.Request.Url.Scheme, "://", Context.Request.Url.Host, ":", Context.Request.Url.Port, "/", Context.Request.ApplicationPath, "/ScriptResource.axd")
oRequest = New HttpRequest("scriptresource.axd", sScriptResourcePath, sUrl.Substring(sUrl.IndexOf("?"c) + 1))
Try
Using oWriter As New StringWriter(m_ScriptBuilder)
Dim oHandler As IHttpHandler = New System.Web.Handlers.ScriptResourceHandler
oHandler.ProcessRequest(New HttpContext(oRequest, New HttpResponse(oWriter)))
End Using
Catch theException As Exception
Call ReportError(theException)
' Since we couldn't automatically process this, just bail so that standard processing takes over
Return
End Try
Else
' If this script is from a file, open the file and load the
' contents of the file into the compiled js variable
Dim sAbsolutePath As String
sAbsolutePath = Context.Server.MapPath(oElement.Path)
Try
If System.IO.File.Exists(sAbsolutePath) Then
Using oReader As New StreamReader(sAbsolutePath, True)
m_ScriptBuilder.Append(oReader.ReadToEnd())
End Using
Else
Throw New Exception("File " & sAbsolutePath & " does not exist")
End If
Catch theException As Exception
Call ReportError(theException, New ExtraErrorInformation("File", sAbsolutePath))
' Since we couldn't automatically process this, just bail so that standard processing takes over
Return
End Try
End If
m_ScriptBuilder.AppendLine()
' add this script to the script reference library
Dim oNewElement As New ScriptReference
oNewElement.Name = e.Script.Name.ToString()
oNewElement.Assembly = e.Script.Assembly.ToString()
oNewElement.Path = e.Script.Path.ToString()
m_cScripts.Add(oNewElement)
End If
End If
' a script filename is provided for caching
e.Script.Assembly = String.Empty
e.Script.Name = String.Empty
e.Script.Path = Me.ScriptFileName
Catch theException As Exception
HttpContext.Current.Response.Write(ReportError(theException))
HttpContext.Current.Response.End()
End Try
End Sub
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
' Exceptions are handled by the caller
MyBase.Render(writer)
If Not m_fIsCached Then
If Not String.IsNullOrEmpty(Me.ScriptName) Then
' Save script to file for caching
Using fsFile As New FileStream(Me.Page.Server.MapPath(Me.ScriptFileName), FileMode.Create, FileAccess.Write, FileShare.Read)
Using oWriter As New StreamWriter(fsFile)
oWriter.Write(m_ScriptBuilder.ToString)
oWriter.Flush()
oWriter.Close()
End Using
fsFile.Close()
End Using
' Record that the script file has been cached
Configuration.RecordPageScriptCached(Me.ScriptFileName)
End If
m_ScriptBuilder = Nothing
End If
End Sub
Private Function GetUrl(ByVal oReference As ScriptReference) As String
' Exceptions are handled by the caller
If String.IsNullOrEmpty(oReference.Path) Then
Try
Dim oMethod As MethodInfo
oMethod = oReference.GetType.GetMethod("GetUrl", BindingFlags.NonPublic Or BindingFlags.Instance)
If oMethod IsNot Nothing Then
Return DirectCast(oMethod.Invoke(oReference, New Object() {Me, False}), String)
Else
Return String.Empty
End If
Catch ex As Exception
Return String.Empty
End Try
Else
Return Me.ResolveClientUrl(oReference.Path)
End If
End Function
End Class
In the above code, ReportError logs the exception to the event log and/or file; you can replace this with your own mechanism.
Here is the Configuration code:
Private Shared m_cCachedPageScripts As Collections.Generic.List(Of String)
''' <summary>
''' This method is used to determine whether or not the script for the page has been cached.
''' This is used for script combining.
''' </summary>
''' <param name="sKey"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function HasPageScriptBeenCached(ByVal sKey As String) As Boolean
' Exceptions are handled by the caller
SyncLock CacheSyncObject
If m_cCachedPageScripts IsNot Nothing AndAlso m_cCachedPageScripts.Contains(sKey) Then
Return True
End If
End SyncLock
End Function
''' <summary>
''' This method is used to record the fact that the page script has been cached.
''' This is used for script combining.
''' </summary>
''' <param name="sKey"></param>
''' <remarks></remarks>
Public Shared Sub RecordPageScriptCached(ByVal sKey As String)
' Exceptions are handled by the caller
SyncLock CacheSyncObject
If m_cCachedPageScripts Is Nothing Then
m_cCachedPageScripts.Add(sKey)
End If
m_cCachedPageScripts.Add(sKey)
End SyncLock
End Sub

Categories