Getting confirm value in code behind - javascript

i have a pop up on the index change of a combo box and i need to get the result of the confirm box in the code behind:
Protected Sub service_list_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles service_list.SelectedIndexChanged
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "confirm", x.javaMsg("Do you
want to choose a date?"), True)
If user clicks ok
GridView1.DataSource = x.selectCNT(service_list.SelectedValue)
GridView1.DataBind()
End Sub
this is my function:
Public Function javaMsg(ByVal message As String) As String
Dim sb As New System.Text.StringBuilder()
sb.Append("window.onload=function(){")
sb.Append("confirm('")
sb.Append(message)
sb.Append("')};")
Return sb.ToString()
End Function
note that i'm using asp.net with vb.net

Here is a link that shows how to do it: Call VB method from JavaScript
It basically says there are 2 ways, Ajax or Postback. Here is the postback method:
aspx file:
<script type="text/javascript">
<!--
function callServersideFunction()
{
var someValueToPass = 'Hello server';
__doPostBack('CustomPostBack', someValueToPass);
}
// -->
</script>
aspx.vb file:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
' Insure that the __doPostBack() JavaScript method is created...
Me.ClientScript.GetPostBackEventReference(Me, String.Empty)
If Me.IsPostBack Then
Dim eventTarget As String
Dim eventArgument As String
If ( (Me.Request("__EVENTTARGET") Is Nothing)
eventTarget = String.Empty
Else
eventTarget = Me.Request("__EVENTTARGET"))
If ( (Me.Request("__EVENTARGUMENT") Is Nothing)
eventArgument = String.Empty
Else
eventArgument = Me.Request("__EVENTARGUMENT"))
If eventTarget = "CustomPostBack" Then
Dim valuePassed As String = eventArgument
' Call your VB method here...
End If
End If
End Sub

Related

ASP.net loading just data onload instead of page HTML

I am having some issues with just wanting to output some data to the page without having all the HTML load. I am using AJAX to call the same ASPX page in order to populate some data to be returned to the AJAX call. However, it currently does call and it does populate with the correct data BUT it does not seem to want to place that data onto the page.
It currently has an error loading the page of "This webpage is not available: ERR_CONNECTION_RESET"
When I load the page like so:
http://localhost:2765/Default.aspx?Data=viewData
is where I receive the error of "This webpage is not available: ERR_CONNECTION_RESET". Placing some code breaks in, I can confirm that it does populated the needed data but never seems to display it on the page and it also seems to call the page at least 2 times before finally stopping (possibly causing the error above).
The default.aspx code is this:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="AdminPanel._default" %>
<% If loadHTMLPage Then %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
....[more HTML code here]....
<script type="text/javascript">
$(document).ready(function () {
var clickedButtonName = "";
$('#dashboardData, #viewData, #updateData, #addData, #deleteData').click(function() {
clickedButtonName = '#' + $(this).attr("id");
$.ajax({
url: $(this).attr("id") + ".aspx",
dataType: 'html',
timeout: 10000,
success: function (html) {
$("#jQueryLoadHere").html(html);
$('#dashName').html("<strong>" + $(clickedButtonName).data("title") + "</strong> Page");
$('#dashboardData_LI, #viewData_LI, #updateData_LI, #addData_LI, #deleteData_LI').attr('class', 'nav-parent');
$(clickedButtonName + '_LI').attr('class', 'nav-parent nav-active active');
}
});
});
});
</script>
</form>
</body>
</html>
<% Else %>
<% =pageData %>
<% End If %>
The codebehind is this:
Public Class _default
Inherits System.Web.UI.Page
Dim whatData As String = Nothing
Public loadHTMLPage As Boolean = True
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
whatData = Request.QueryString("Data")
Response.Write(whatData)
If whatData = "viewData" And hasLoaded = False Then
loadHTMLPage = False
hasLoaded = True
Call workingGetFEBList()
End If
End Sub
Private Sub workingGetFEBList()
Dim request As WebRequest = WebRequest.Create(apiURL & appID & "/" & formID & "?format=text/xml")
request.Method = "GET"
request.Credentials = CredentialCache.DefaultCredentials
Dim response1 As WebResponse = request.GetResponse()
Dim dataStream As Stream = response1.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim serverResponse As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
Response.Close()
Dim theOutput As String = parseXML2JSON(serverResponse)
pageData = theOutput
End Sub
If I comment out:
Call workingGetFEBList()
pageData = theOutput
and refresh the page - it works just fine loading the page (blank white page with just viewData text on it).
Likewise, just loading the page:
http://localhost:2765/Default.aspx
Loads up the page with the normal HTML just fine.
So what could I be missing??

Whats wrong in this asp.net code? Textbox value doesnt set

protected void Button1_Click(object sender, EventArgs e)
{
if (count > 100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById(\" <%=TextBox1.ClientID%>\").value=\"1\"; alert(document.getElementById(\"<%=TextBox1.ClientID %>\").value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
Here I want to set the value of the textbox by clicking the button event and oly that condition is true.So I cant call that function from source.actually that function gets called but the textbox value doesnt set..I really dont understand where is the problem..
protected void Button1_Click(object sender, EventArgs e)
{
if(count>100)
{
StringBuilder javascript = new StringBuilder();
javascript.Append(" <script language=\"javascript\" type=\"text/javascript\">");
javascript.Append(" var tmp = confirm(\"No:Of Records exceeds 1000.Please confirm you want to continue\");");
javascript.Append("if (tmp)");
javascript.Append("{document.getElementById('" + TextBox1.ClientID + "').value=\"1\"; alert(document.getElementById('" + TextBox1.ClientID+ "').value);}");
javascript.Append(" </script>");
ClientScript.RegisterStartupScript(GetType(), "recordscript", javascript.ToString(), false);
return;
}
}
}
You need to concatenate the TextBox1.ClientID with your javascript string. The code you have will get rendered to the page as is, look at the output of your rendered page with view source, you will see the string '<%= TextBox1.ClientID =%>' not the expected ID. Keep in mind that the inline display expression <%= =%> is equivalent to a server Response.Write().

Change page from an Iframe to the Main Window

I'm working inside an iframe and when i finish my job I want to change page (NOT inside iframe) but out side of this iframe, in the main window.
For this I use the following Sub:
Public Sub ChangePage(sender As Object, e As EventArgs)
Dim myNewAsp As New AspNetSqlProvider
Dim dbHandler As New DBHandler
Dim srvHandler As New ServerHandler
Dim aspProvider As New MyAspNetSqlMembershipProvider
Dim errAnswer As New Register
Dim assit As New Assistance
Dim currentUser As MembershipUser = Nothing
Dim message As String = Nothing
Dim msg As String = Nothing
Try
Dim url As String = "/Pages/Account/Login.aspx"
Dim postWindow As Object ' "/Pages/Account/Assistance.aspx"
Dim startWindow As Object ' "/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)
url = myServerName + url
startWindow = Me.GetType().FullName
postWindow = Assistance.PageUrlType
msg = "Hellow World"
'msg = "<script type='text/javascript'> $(document).ready(function(){ window.location.href='" + url + "'; }); </script>"
Dim script As Type = Me.Page.GetType() ' Assistance.PageType.BaseType
Dim postmsg As String = "ChangePage('" & startWindow & "', '" & postWindow & "', '" & msg & "')"
If Not Page.ClientScript.IsStartupScriptRegistered(Me.GetType(), "sendMessage") Then
Page.ClientScript.RegisterStartupScript(script, "sendMessage", postmsg)
End If
Catch eq As SqlException
srvHandler.ErrorAnswer = DBHandler.GetError(1, Nothing, Nothing, eq, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword "
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
Catch Ex As Exception
srvHandler.ErrorAnswer = DBHandler.GetError(3, Ex, Nothing, Nothing, Nothing)
srvHandler.ErrorAnswer = srvHandler.ErrorAnswer & "\r\n Asp.SQLProvider.ResetPassword"
ServerHandler._InnerError += srvHandler.ErrorAnswer
Register.errorCall = True
Return
End Try
End Sub
I use the following script in the Page inside the iFrame:
<script type="text/javascript">
function ChangePage(startPage, sendPage, message) {
var sPage = document.getElementById(startPage);
sPage.contentWindow.postMessage(message, sendPage);
}
</script>
I also use the following script in the Page I want to change (parent Page):
<script type="text/javascript">
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
event.origin !== message;
event.source.postMessage("'" + message + "'", event.origin);
return;
}
what I got from the above is to have the desired page (the message in the example) BUT inside of the frame.
The scrip in the Help01.aspx page is executed just fine. But in this window, and not in the parent one (Assistance,aspx)
As a result I can't get out of the iFrame (which is inside of a table).
Is someone to know what to do about it?
I think you'll need to use something like postMessage here. It depends on the browsers you need to support, but support is pretty good. That will let you "talk" between the main window and the iFrame.
That link will walk you through how to set it up, but the gist of it is that you'll need to attach an event listener to the main window and then post a message from the iFrame to the outer window. Then do your redirect in the outer window when the message comes in.
So where you have Dim msg As String... you'll want that to be some code that posts a message to the outer frame. Something like window.postMessage(..)

Calling Code-behind from Javascript

On the click of a button, I call a JavaScript function. After getting the value, I need to perform some stuff from the value obtained in the code-behind. How should I call code-behind?
My aspx:
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
//After this I need to perform stuff 'Upload(TxtInput.value)' into database from the code-behind
}
The button calling the function is set up in the following manner:
<button class="doActionButton" id="btnSelectImage" runat="server" onclick="openWindow('../rcwksheet/popups/uploader.htm')">Select Image</button>
My desired code behind (VB):
Public Sub btnSaveImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSelectImage.ServerClick
Dim inputFile As String = Me.TxtInput.Value
//do more stuff here
End Sub
So:
Is there a way to call code-behind from the JavaScript?
Can I somehow use the "onclick" property of a button to first go to a JavaScript and then to the code-behind?
Trigger a code-behind call "onchange" of the TxtInput.Value?
yes there is a way.
first, you can use javascript to submit the form after your return value is set in TxtInput.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
document.forms[0].submit();
}
then in your code behind, you can handle TxtInput's value in page load event.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (this.Input.Value != string.Empty)
{
this.Input.Value += "blah";
}
}
}
note: you may need Identifying control that caused postback
You can put the server side code into a web service, make a service reference in an asp:ScriptManager on your aspx page and then you can call/execute the web service from javascript by calling:
WebServiceClassName.MethodName(javascriptvariable, doSomethingOnSuccess)
Here is a link on doing that:
http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
You can call the __doPostBack Event.
function openWindow(page) {
var getval = window.showModalDialog(page);
document.getElementById("<%= TxtInput.ClientID %>").value = getval;
__doPostBack('btnSelectImage', getval);
}
And on the server side in your code behind, you can get the value:
In the PageLoad method:
if (Request.Form["__EVENTTARGET"] == "btnSelectImage")
{
//get the argument passed
string parameter = Request["__EVENTARGUMENT"];
//fire event
btnSaveImage_Click(this, new EventArgs());
}

Javascript posting to VB.Net page multiple times

Greetings,
Upon a javascript button click, I'm using jquery to post to a url:
$(".optionClick").click(function () {
var caseOption = $(this).attr('title');
$.post("../tracking/RecordClick.aspx?page=gallery&item=" + caseOption);
});
On the page being called, I'm using the following vb.net code to retrieve the querystring variables and write them to a database:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Request.QueryString("page") Is Nothing Then
Dim trackingPage As String = Request.QueryString("page")
Dim trackingIP As String = Request.UserHostAddress
Dim trackingItem As String = Request.QueryString("item")
Dim trackingDate As String = Date.Now().ToString("G")
Try
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
Select Case trackingPage
Case "gallery"
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO UserTrackGallery VALUES ('" & trackingIP & "', '" & trackingItem & "', '" & trackingDate & "')"
cmd.Connection = sqlCon
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Case "products"
Case "search"
End Select
Catch ex As Exception
End Try
Response.Close()
End If
End Sub
In local development, this works perfectly for me recording one database write per button click. On the server however, each post generates anywhere from 1 to 7 database writes.
I've been searching for a solution for a couple of days to no avail. Any help is greatly appreciated!
------------------------------Update--------------------------------
I tried to simplify the process by creating a VB.Net page with only a single button:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="javascript.aspx.vb" Inherits="gallery_javascript" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="../Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({ async: false });
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" class="optionClick" value="button" />
</div>
</form>
</body>
</html>
But the problem persists. Firebug reports "Aborted" and the page is called multiple times. I also tried this javascript:
$(document).ready(function () {
$.ajaxSetup({ url: '../tracking/RecordClick.aspx' });
$(".optionClick").click(function () {
$.ajax({ data: 'page=gallery&type=click&item=XYZ' });
});
});
Tried this also:
url = "../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ";
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
try {
req.open("POST", url, false);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.open("POST", url, false);
req.send();
}
}
Each of the javascript blocks above worked locally as intended but failed in the same manner with multiple DB writes and Firebug "Aborted" status.
If I call the url+querystring directly via the browser, everything works as expected.
Could this be related to a delay of some sort since it works locally?
Thanks for the help thus far!
(Edit) Also tried using the full path url in the code above - no improvement.
I found a solution to my problem. It appears that the more recent versions of .Net prevent HTTP POST calls, but this is allowed for localhost (which is why it worked perfectly locally). HTTPWatch and Firebug both showed the .aspx page connection but no response returned. It appears as though the multiple calls were retry attempts to receive a response.
My solution was to create a web service:
Option Strict On
Imports System.Data.SqlClient
Imports System.Data
Imports System
Imports System.Net
Imports System.Text
Imports System.IO
Imports System.Web.HttpContext
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://mywebsite.com/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class RecordClick
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function RecordClick() As String
Dim trackingPage As String = ""
Dim trackingIP As String = ""
Dim trackingType As String = ""
Dim trackingItem As String = ""
Dim trackingDate As String = ""
With HttpContext.Current
trackingPage = .Request.Params.Item(0)
trackingIP = .Request.UserHostAddress
trackingType = .Request.Params.Item(1)
trackingItem = .Request.Params.Item(2)
trackingDate = Date.Now().ToString("G")
End With
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("SSFDBConnectionString").ConnectionString
Dim sqlCon As New SqlConnection(conString)
Dim cmd As New SqlCommand
cmd.Connection = sqlCon
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "spInsertRecordClick"
cmd.Parameters.Add("#IPAddress", SqlDbType.NVarChar, 50)
cmd.Parameters("#IPAddress").Direction = ParameterDirection.Input
If trackingIP = "" Then
cmd.Parameters("#IPAddress").Value = DBNull.Value
Else
cmd.Parameters("#IPAddress").Value = trackingIP
End If
cmd.Parameters.Add("#CaseOption", SqlDbType.NVarChar, 50)
cmd.Parameters("#CaseOption").Direction = ParameterDirection.Input
If trackingItem = "" Then
cmd.Parameters("#CaseOption").Value = DBNull.Value
Else
cmd.Parameters("#CaseOption").Value = trackingItem
End If
cmd.Parameters.Add("#TimeDate", SqlDbType.DateTime)
cmd.Parameters("#TimeDate").Direction = ParameterDirection.Input
If trackingDate = "" Then
cmd.Parameters("#TimeDate").Value = DBNull.Value
Else
cmd.Parameters("#TimeDate").Value = trackingDate
End If
cmd.Parameters.Add("#ViewType", SqlDbType.NChar, 10)
cmd.Parameters("#ViewType").Direction = ParameterDirection.Input
If trackingType = "" Then
cmd.Parameters("#ViewType").Value = DBNull.Value
Else
cmd.Parameters("#ViewType").Value = trackingType
End If
cmd.Parameters.Add("#Page", SqlDbType.NVarChar, 50)
cmd.Parameters("#Page").Direction = ParameterDirection.Input
If trackingPage = "" Then
cmd.Parameters("#Page").Value = DBNull.Value
Else
cmd.Parameters("#Page").Value = trackingPage
End If
Try
If sqlCon.State = ConnectionState.Closed Then
sqlCon.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Finally
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
End Try
If sqlCon.State = ConnectionState.Open Then
sqlCon.Close()
End If
Return "Success"
End Function
End Class
This is the javascript I used to call the web service:
$.ajax({
type: "POST",
url: "../tracking/RecordClick.asmx/RecordClick",
data: "page=" + DMOriginatingPage + "&type=" + DMType + "&item=" + DMtitle
});
I had to add the following to the system.web section of the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
It works perfectly now. I'm not very experienced in this area so there's probably a better solution for what I'm trying to do. However, maybe this will help someone else - took me two weeks to figure this out. :)
I would suggest tracing the problem.
1) Use Firefox + Firebug, open the NET tab and watch how many requests are sent.
2) Paste your AJAX URL in your browser's address bar and see what happens on the server. This way you are sure only one request is made.
Have you tried using the full path from the root of the site in the post call...instead of using the "../"?
Suspect code:
$(".optionClick").click(function () {
$.post("../tracking/RecordClick.aspx?page=gallery&type=click&item=XYZ");
});
try removing the ".." and replacing it with the actual path...I am suspicious that that could be causing your problem.

Categories

Resources