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()" />
Related
I have an issue in getting the hidden field values, which is been set in page load at code behind. Problem is when i try to get that set values in javascript its giving undefined or null. Not able to get the values which was set in page load at code behind.
//cs code is like this
protected async void Page_Load(object sender, EventArgs e)
{
HiddenField_alt_edit.Value = "[{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type=text/javascript>addAlternativeRowWithData();</script>");
}
//aspx page declaration goes like this. Also i am using a master page.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on."/>
</asp:Content>
// javascript file code goes like this
function addAlternativeRowWithData(mode)
{
alert("test");
var idvalue = $("#HiddenField_alt_edit").val();
alert(idvalue);
alert($nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val());
var myHidden = document.getElementById('<%= HiddenField_alt_edit.ClientID %>').value;
alert(myHidden);
var json_string = $nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val();
var arr_from_json = JSON.parse(json_string);
alert("test 2");
alert(arr_from_json);
}
The id generated at client side can differ as the Hidden field is server side control in your code as you have set runat="server".
There are two ways normally. Either make the ClientIDMode static or use the instance in form to get client side id.
Like:
<asp:HiddenField ID="HiddenField_alt_edit" ClientIDMode="static" runat="server"
Value="i am on."/>
and then following should work:
var idvalue = $("#HiddenField_alt_edit.ClientID").val();
or in client side code you need to get id like below:
var idvalue = $("#<%= HiddenField_alt_edit.ClientID %>").val();
Change:
HiddenField_alt_edit.Value = [{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]
To this:
HiddenField_alt_edit.Value = "
[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]"
Then, add this:
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on." ClientIDMode="Static" />
In you js, you have to put this:
const value = document.getElementById('HiddenField_alt_edit').value
const jsonString = JSON.stringify(value)
const json = JSON.parse(jsonString)
console.log(json)
<input hidden id="HiddenField_alt_edit" value="[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]">
i have a radwindow that is being opened by a view column from a rad grid. but the thing is that nothing is happening , the window is not even opening!!!
i want to passe 2 parameters to the RadWindow.
this is the javascript im using:
function ShowEditForm(IdVoiture, IdType, rowIndex) {
var grid = $find("<%= RadGrid1.ClientID %>");
var rowControl = grid.get_masterTableView().get_dataItems()[rowIndex].get_element(); grid.get_masterTableView().selectItem(rowControl, true);
window.radopen("ViewForm.aspx?IdVoiture=" + IdVoiture, "&IdType=" + IdType,"UserListDialog");
return false;
}
and this is my column code from the radGrid:
<telerik:GridTemplateColumn UniqueName="TemplateViewColumn">
<ItemTemplate>
<asp:HyperLink ID="ViewLink" runat="server" Text="View"></asp:HyperLink>
</ItemTemplate>
</telerik:GridTemplateColumn>
this is the code behind:
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As GridItemEventArgs)
If TypeOf e.Item Is GridDataItem Then
Dim editLink As HyperLink = DirectCast(e.Item.FindControl("ViewLink"), HyperLink)
editLink.Attributes("href") = "#"
editLink.Attributes("onclick") = [String].Format("return ShowEditForm2('{0}','{1}');", e.Item.OwnerTableView.DataKeyValues(e.Item.ItemIndex)("DepIDVoit"), 4, e.Item.ItemIndex)
End If
End Sub
i'm not able to locate my error and i tried to do the same as other examples it is still not working please help!!!
****Mark that my code is in an .ascx page contained inside an multipage in a .aspx page , and the javascript is in the .aspx page i dont know if that makes any differencs
i figured out what was missing. my javascript code was correct but my page was missing a RadWindowManager
I have a small problem . If page is refreshed using F5 , TextBox should preserve its old value . In Page_Load() , if i keep // Loading(); then TextBox1 preserve its old value.
As soon as i remove comment , it loose value in TextBox1 .
Please tell me the reason behind it and What should be done to avoid it .
<script type="text/javascript">
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
function getMyvalSession() {
var ff = "Loading Value";
return ff;
}
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" Name="TextBox1" runat="server"
AutoPostBack='true' onchange="TextBox1_TextChanged()"></asp:TextBox>
<%
string x = null;
x = Session["HitCount1"].ToString().Trim();
if ((x.Equals(null)) || (x.Equals("")))
{
// Session Variable is either empty or null .
}
else
{
TextBox1.Text = Session["HitCount1"].ToString();
}
%>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{
// Loading();
}
void Loading()
{
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
Combining inline server-side code and code-behind code is generally a bad idea. I would recommend just using the code-behind code.
This code:
function TextBox1_TextChanged() {
<%
Session["HitCount1"] = TextBox1.Text ;
%>
}
... is not going to have the effect of the (server-side) Session entry "HitCount1" getting set to Textbox1.Text, because TextBox1_TextChanged is a client-side function, and your assignment statement is going to happen on the server side. At run time, the chunk of server code will have been removed by the compiler, so TextBox1_TextChanged will be an empty function.
The rule of thumb: Things happen on the client, or they happen on the server on postback, or they happen on the server via Ajax calls. You can't mix client and server code together.
My recommendation: switch to doing everything in code-behind. When you have it working, if you have too many postbacks, investigate Ajax calls.
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";
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.