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.
I want to show part of page: web form which will be filled by user.
That web form is inside this tag:
In Java, I am trying to get form by class its name(because there is only one tag with class name "form"). Then I am trying to change content with "form" content(maybe I am doing this wrong). Then trying to show content(only form) in webview.
final WebView webview = (WebView) view.findViewById(R.id.wvCheckInn);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
String javascript = "javascript: var form = document.getElementsByClassName('form');"
+ "var body = document.getElementsByTagName('body');"
+ "body.innerHTML = form.innerHTML;";
view.loadUrl(javascript);
}
});
webview.loadUrl("http://businessinfo.uz/service/inn");
Result: webview is showing whole page, which is not good for me. How to show part of page in Webview using Javascript?
In your javascript, document.getElementsByClassName() and document.getElementsByTagName() both return arrays of DOM elements (notice the 's's before "By".) This is different from getElementById(), which returns an element directly, which makes sense since IDs are unique across a valid HTML document, but tags and classes are not.
Access the first element from each array and the javascript works:
body[0].innerHTML = form[0].innerHTML;
I have a problem , I am quite new to this whole coding in cross languages , basically when I click on a row index in my GridView it then opens a new tab and brings in the results in that window ( The new one that has just opened ) and I know this is from using the Window.Open but I am wondering is there a function that I can use to just open my results in the actual same window from where it is being clicked? something like Window.Open <Open in same window>? My code is below.
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(1).Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';"
e.Row.Cells(1).Attributes("onmouseout") = "this.style.textDecoration='none';"
Dim Index As Integer = e.Row.RowIndex
e.Row.Cells(1).Attributes("OnClick") = "window.open('MachineSweepLite.aspx?AreaID=" + GridView1.DataKeys(e.Row.RowIndex).Values("ID").ToString + "');"
End If
End Sub
Please make your answers Clear as possible for me to understand.
Instead of window.open() use window.location.href like the following
window.location.href = 'http://www.google.com';
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.
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