Passing Variable from JS to VB.net - javascript

I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.
I have tried putting the variable into a label then grabbing it from the label in vb.net as shown in the code below:
Js part.
document.getElementById("Label1").innerText = nwLat;
then in the vb part
Dim nwLat As Double
nwLat = Label1.Text
MsgBox(nwLat)
it does not work for me any ideas? the error that comes up is
Input string was not in a correct format.
Cheers!

Easiest way without any type of ajax would be to use a hidden field.
Markup:
<asp:HiddenField ID="nwLatHidden" runat="server" Value="" />
JS:
document.getElementById('nwLatHidden').value = '6.00'; // or of course the value from your function.
.NET during your postback routine:
Dim nwLat As Double
nwLat = nwLatHidden.Value

In JavaScript:
__doPostBack(
'edit',
JSON.stringify({ ID: id, Code: code, AcctNo: acctNo })
);
In VB.NET:
Protected Sub Page_Load(s As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'...
Else
Dim eventTarget As String = Request.Form!__EVENTTARGET
Dim eventArgument As String = Request.Form!__EVENTARGUMENT
If Not eventArgument Is Nothing AndAlso Not eventTarget Is Nothing AndAlso eventTarget = "edit" Then
Dim jss As New JavaScriptSerializer()
Dim ac As AccountCode = jss.Deserialize(Of AccountCode)(eventArgument)
End If
End If
End Sub

You need to use the ClientID or the UniqueID:
document.getElementById("<%=Label1.UniqueID%>").innerText = "Hi";

Related

Adding a Javascript alert on successful form submission - VB.Net

I'm trying to add an alert when a user submits a form. I want it to only show the alert when the submit is successful, otherwise I would just attach a javascript alert to the submit button. I followed the method suggested here:
http://www.aspsnippets.com/Articles/Dsplay-Alert-Message-in-ASPNet-from-code-behind-using-C-and-VBNet.aspx
but the alert part isn't working. I tried putting the alert code in the Page_Load and it worked, but when I put it in the button click handler, I don't get any alert.
Public Sub Send_Data(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNewsletter.Click
Dim sFName, sLName As String
Dim sEmail As String
Dim clsUser As New clsLogin
Dim iConfirm As Integer
sEmail = email.Text
If sEmail = "" Then Exit Sub
Try
If clsUser.Check_Cookie = False Then
iConfirm = clsUser.Create_Acct("", "", sEmail, "", iType)
End If
clsUser.Add_AvailLog(0, iType, iChat)
Catch
End Try
'start JK
Dim blog As Destinations.GetBlog
Dim TargetURL As String
TargetURL = "http://wimco.us8.list-manage.com/subscribe/post?u=fe50a5183f6f54bb70a7005e3&id=b2e21157fc"
Dim html As String
Dim PostData As String
PostData = "&EMAIL=" & sEmail & "&b_fe50a5183f6f54bb70a7005e3_b2e21157fc=&subscribe=Subscribe"
html = blog.PostData(TargetURL, PostData)
email.Text = ""
' This is the alert section
Dim message As String = "Order Placed Successfully."
Dim sb As New System.Text.StringBuilder()
sb.Append("<script type = 'text/javascript'>")
sb.Append("alert('")
sb.Append(message)
sb.Append("');")
sb.Append("</script>")
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", sb.ToString())
End Sub
I have been doing something similar to this and your code looks ok.
Have you tried to debug your code and made sure the code reaches the end of the Send_Data function where RegisterClientScriptBlock is called?
I have a feeling it stopped at If sEmail = "" Then Exit Sub.
You have to put the alert to the page which is shown after the submitted page.

Access OwnerTableView ParentItem

It is my Vb.net code it works perfectly.
Protected Sub ChkTaxCheckedChanged1(ByVal sender As Object, ByVal e As EventArgs)
Dim chkTax As CheckBox
Dim gv1 As GridDataItem
chkTax = TryCast(sender, CheckBox)
gv1 = DirectCast(chkTax.NamingContainer, GridDataItem)
Dim txtAmount1 As Label = CType(gv1.OwnerTableView.ParentItem.FindControl("lblItemAmount"), Label)
End Sub
But now I want to achieve the same functionality in clientside using JavaScript.
Like :
function ChkTaxCheckedChanged1(sender, args) {
var check = sender.get_parent()..??????
}
Any one know how can I do this?
Try this.
<script>
function handleClick(sender,args) {
//i have used jquery so do not forgot add jquery reference
var checkboxid = sender.get_id();
var parentRow = checkboxid.parent().parent().parent().parent().parent().parent()[0].previousSibling;
$(parentRow).find('span').html('Your text comes here');
}
</script>

textbox value from client side in code behind?

I'm writing a website that is fully dynamic . means all controls are made by Response.write , no I have a problem , that after page load I want to get value of text boxs which made dynamically in code behind , but its not received by Request.Form , here is my code :
Private Function userconf() As string
Dim script As String
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
Dim com As New SqlCommand("SELECT * FROM clientamount WHERE Mode <> 1 ", con)
con.Open()
Dim resultid As String
Dim reader As SqlDataReader = com.ExecuteReader()
Try
While reader.Read()
RenderBuyForm = RenderBuyForm + "<div><input id='tx" & reader("ID") & "' type='text' />" & reader("avrageamountunit") & "<input id='txd" & reader("ID") & "' type='text'/>"
End While
Finally
reader.Close()
End Try
End Using
Return RenderBuyForm
End Function
and this function loads in page_preload event :
Protected Sub Page_PreLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreLoad
userconf()
End If
End Sub
and also in html page I have
<form id="form1" runat="server">
<%=RenderBuyForm%>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
at least I try to read textboxes value are in html page now in Button1_Click event:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each row As DataRow In tabel1.Rows
Dim a As String = Request.Form("tx" & tabel1.Rows(0)("ID") & "")
label1.text = a
Next
End Sub
but a is returning Nothing . can I ask you help me in this issue ? how can I read these textboxes value from client side in code behind ?
You will also need to add to
RenderBuyForm = RenderBuyForm + "<div><input id='tx" ....
RenderBuyForm = RenderBuyForm + "<div><input name='tx' & reader("ID") ..
in the userconf().

Calling JS function from ASP.NET codebehind

I have two javascript functions in my aspx page. They use some fabric.js functions.
function saveCanvas() {
js = JSON.stringify(canvas.toDatalessJSON());
$get('<%= txtJSON.ClientID%>').value = js;
}
function loadCanvas() {
js = $get('<%= txtJSON.ClientID%>').value;
canvas.clear();
canvas.loadFromDatalessJSON(js);
canvas.renderAll();
}
And in the codebehind:
Protected Sub SaveJSON()
Dim scriptKey As String = "123"
Dim javaScript As String = "<script type='text/javascript'>saveCanvas();</script>"
ClientScript.RegisterStartupScript(Me.GetType(), scriptKey, javaScript)
End Sub
Protected Sub LoadJSON()
Dim scriptKey As String = "456"
Dim javaScript As String = "<script type='text/javascript'>loadCanvas();</script>"
ClientScript.RegisterStartupScript(Me.GetType(), scriptKey, javaScript)
End Sub
Now my question: Why does loadCanvas work while saveCanvas does not? txtJSON is not populated with the JSON-string.
Calling the saveCanvas function from the aspx page works fine.
The problem is that you call saveCanvas after the postback is done and at that point the canvas data is long gone.
If you have a button "Save" then you need to call saveCanvas when it is clicked so that the data is saved before the browser posts the page back to the server:
<asp:Button runat="server" Text="Save" OnClickClick="saveCanvas()" />

Set selectedvalue for a dropdownlist using Javascript

I have a dropdownlist that is populated by a webservice using the ajax cascading dropdown. I have not been able to set the selected value using javascript. It appears that the values do not exist when the javascript runs. I placed the javascript at the bottom of the aspx page. Any ideas. Here is all of the code and the javascript I have tried.
<asp:DropDownList ID="ddlBusinessArea" runat="server"></asp:DropDownList>
<cc1:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="ddlBusinessArea"
Category="BusinessArea" ServiceMethod="GetBusinessArea" ServicePath="DropDownFilter.asmx"
LoadingText="Please Wait.....">
</cc1:CascadingDropDown>
<WebMethod()> _
Public Function GetBusinessArea() As CascadingDropDownNameValue()
Dim values As New List(Of CascadingDropDownNameValue)()
Dim objData As clsDataAccess = New clsDataAccess()
Dim ds As DataSet = New DataSet
Dim SQL = "select Description from tblvalidation where MyType = 'Business Area' order by description"
ds = objData.SQLExecuteDataset(SQL)
For Each dr As DataRow In ds.Tables(0).Rows
values.Add(New CascadingDropDownNameValue(dr("Description"), dr("Description")))
Next
Return values.ToArray
End Function
<script type="text/javascript">
var e = document.getElementById("<%=ddlBusinessArea.ClientID%>");
e.options[e.selectedIndex].value = "12345"
document.getElementById("<%=ddlBusinessArea.ClientID%>").value = "12345"
document.getElementById("ctl00_ContentPlaceHolder2_ddlBusinessArea").value = "12345"
</script>
No, you cannot set the value from code-behind; you would have to use JavaScript to set the selected value if binding from a web service. The web service binds everything after the server-side process runs and can only be affected by javascript.
HTH.

Categories