How to get client side value from server side using VB.NET? - javascript

I have an ASPX page where I set data with JS but I am having a bad time trying to get this data from VB.
This is a simplified version of what I have...
ASPX:
<body onload="DoStuff();">
<script>
function DoStuff() {
var myvalue = document.getElementById('lblValue');
myvalue.textContent = "blah";
console.log (myvalue.textContent); // just to be sure that the value IS there
}
</script>
<div style="display:block">
<asp:label id="lblText" visible="true" runat="server">Text: </asp:label><asp:label id="lblValue" runat="server" visible="true" ></asp:label><br /><br />
<asp:label id="lblMsg" visible="true" runat="server" >Message: </asp:label><asp:label id="lblMsgValue" runat="server" visible="true" >Click button...</asp:label><br /><br />
<asp:Button id="btnGo" Text="Go" OnClick="btnGo_Click" runat="server"/>
</div>
</body>
ASPX.VB:
Protected Sub btnGo_Click(sender As Object, e As EventArgs)
lblMsgValue.Text = "The value is *" & lblValue.Text & "*"
End Sub
I am always getting nothing as output. Any idea?

How interesting. I had NEVER noticed that a label set client side does NOT persist.
Note that if you use code behind, set a label.Text, then the label DOES persist and survive a round trip. However, setting the label in JS? Well, you see the browser udpate instant, but when you post back, you lose that text.
This means you need to use say a text box - they DO persist, and even when changed client side.
So, for example this code:
<asp:Button ID="Button2" runat="server"
Text="Js Code" Width="114px"
OnClientClick="setlabel();return false" />
<br />
<asp:Label ID="Label1" runat="server" Text="a" ClientIDMode="Static" ViewStateMode="Enabled"></asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<script>
function setlabel() {
vlable = document.getElementById("Label1");
vlable.innerHTML = 'Hello how are you';
vtextBox = document.getElementById("TextBox1")
vtextBox.value = "Js setup text box"
}
</script>
So, after we run the above button (js), then both the text box, and the label will update and you see the results in the browser.
However, now drop in another button like this:
<asp:Button ID="Button1" runat="server" Height="26px" Text="Set Lable" Width="129px" />
And code behind:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Debug.Print(Label1.Text)
Debug.Print("Text box = " & TextBox1.Text)
End Sub
Output (after running client side js button).
a
Text box = Js setup text box
So we see the Text="a" of the label, while it did change in the browser, when we post back, it does not survive WHEN changed client side.
As noted, if code behind changes a label - it does persist, and does survive around trips. But the label does not.
However, a text box, or hidden field and most controls that show/have the ability to hold data or a value will survive - labels are just not one of those controls.

Related

How to pass Javascript value to label server side

I have a gridview that contains two(2) ASPxComboBox the value of the second Combo box is base on the value of the first combo box. DevExpress demos and sample are a bit complicated and time consuming so I think of a workaround that when the selected item of combo box is exchange the value will store in a label. And I will get the value of label to store in dropdown. But I don't know how to pass the value of label in server side. Any help would be much appreciated. Thank you!
Here's my code.
FrontEnd
<asp:Label ID="LblProduct" runat="server" Text="Label"></asp:Label>
<dx:ASPxGridView ID="ASPxGridView2" OnRowDataBound="ASPxGridView2_RowDataBound" ClientInstanceName="GridV" runat="server" AutoGenerateColumns="False" DataSourceID="forprod" KeyFieldName = "ppdtl_no">
<columns>
<dx:GridViewDataTextColumn FieldName="fld_product" Name="Dd_product" ShowInCustomizationForm="true" VisibleIndex="3">
<SettingsHeaderFilter>
<DateRangePickerSettings EditFormatString="" />
</SettingsHeaderFilter>
<EditItemTemplate>
<dx:ASPxComboBox ID="ASPxComboBoxProduct" runat="server" DataSourceID="pp_prod" TextField="pp_ppname" ValueField="pp_ppcode">
<ClientSideEvents SelectedIndexChanged="function(s, e) { OnProductChanged(s); }"></ClientSideEvents>
</dx:ASPxComboBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
<dx:GridViewDataComboBoxColumn FieldName="fld_type" Name="dd_type" ShowInCustomizationForm="true" VisibleIndex="4">
<SettingsHeaderFilter>
<DateRangePickerSettings EditFormatString="" />
</SettingsHeaderFilter>
<EditItemTemplate>
<dx:ASPxComboBox ID="ASPxComboBoxType" runat="server" DataSourceID="pp_type" TextField="pp_codetype" ValueField="pp_codetype">
</dx:ASPxComboBox>
</EditItemTemplate>
</dx:GridViewDataComboBoxColumn>
</columns>
</ASPxGridView>
JavaScript
function OnProductChanged(s, e) {
var selected_index = s.lastSuccessValue;
var aa = document.getElementById('LblProduct').innerText = selected_index;
}
onload = OnProductChanged;
You need to use the ClientID property of any element you run at server level in your selector. To achieve this, you have to write the JavaScript inside the file with your label, and then use <%= LblProduct.ClientID %>.
<script type="text/javascript">
document.getElementById('<%= LblProduct.ClientID %>');
</script>
Look at your project during runtime with Inspect - you will see the ID after compilation is not LblProduct, but something similar to ProjectName_PageName_ContentPlaceHolderName_LblProduct.
You could also just copy-paste that, though it's not open to change.

Changing Tabs with AspxPageControl

I have a problem about changing tabs in my AspxPageControl.I use this tool for showing my web pages dynamically. When I change my active tab, the old tab vanishes. I searched a bit and found this problem can be fixed with saving states in cache or session.
However I am really rookie about developing web apps. How can I do that ? I also used jquery ui on my project but it didn't work. So I changed my project with this tool. Also I could take advice about tabpages that have dynamic webpages in.
This button basicly adds a new page on my tab and set active page this tab:
protected void bt_yeniEklenenler_Click(object sender, EventArgs e)
{
YeniEklenen_count= YeniEklenen_count + 1;
TabPage tab = new TabPage();
tab.Text = "Yeni Eklenenler";
tab.Name = "tab_yenieklenenler" + YeniEklenen_count.ToString();
LiteralControl l = new LiteralControl("<iframe src='YeniEklenenler.aspx' runat='client' id='frm2' style='width: 99 %; height: 78vh; margin - top:20px'></ iframe >");
l.ID = "lit_yenieklenenler" + YeniEklenen_count.ToString();
tab.Controls.Add(l);
ASPxPageControl1.TabPages.Add(tab);
ASPxPageControl1.ActiveTabPage = ASPxPageControl1.TabPages.FindByName(tab.Name);
}
And my design source:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:ScriptManager runat="server" ID="ScriptManager1">
</asp:ScriptManager>
<asp:Button ID="bt_yeniEklenenler" runat="server" OnClick="bt_yeniEklenenler_Click" Text="Yeni Eklenenler" OnClientClick="ButtonClick();" />
<asp:Button ID="bt_kampanya" runat="server" Text="Kampanya" OnClick="bt_kampanya_Click" />
<asp:Button ID="bt_fiyatListesi" runat="server" Text="Fiyat Listesi" OnClick="bt_fiyatListesi_Click" />
<asp:Button ID="bt_sepetim" runat="server" Text="Sepetim" OnClick="bt_sepetim_Click" />
<asp:Button ID="bt_siparisListesi" runat="server" Text="Sipariş Listesi" OnClick="bt_siparisListesi_Click" />
<asp:Button ID="bt_firmaBilgileri" runat="server" Text="Firma Bilgileri" OnClick="bt_firmaBilgileri_Click" />
<asp:Button ID="bt_cariHareket" runat="server" Text="Cari Hareket" OnClick="bt_cariHareket_Click" />
<asp:Button ID="Button2" runat="server" OnClick="Button1_Click" Text="KAPAT" />
<dx:ASPxPageControl runat="server" ActiveTabIndex="0" RenderMode="Lightweight" Width="1146px" Height="555px" ID="ASPxPageControl1" OnActiveTabChanged="ASPxPageControl1_ActiveTabChanged" AutoPostBack="True">
<TabPages>
<dx:TabPage Text="Ana Sayfa">
<ContentCollection>
<dx:ContentControl runat="server" SupportsDisabledAttribute="True">
<h1 style="text-align:center">_____ SİSTEMİNE HOŞGELDİNİZ...</h1>
<h1 style="text-align:center"> </h1>
<h1 style="text-align:center">
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="KAPAT" />
</h1>
</dx:ContentControl>
</ContentCollection>
</dx:TabPage>
</TabPages>
</dx:ASPxPageControl>
</ContentTemplate>
</asp:UpdatePanel>
Note: I tried turn on AutoPostBack also, but then my tab don't change when I click another tab.
Thanks in advance :)
Refer these:
ASPxPageControl - how to add a new page using Client-Side Scripts
ASPxPageControl - How to add tab on client side
AspxPageControl add tabpage dynamically
You can try adding a tab page using the javascript(client side methods) and after that you can set the active tab. Try using the the client side ASPxClientTabControlBase.SetActiveTab method
ASPxPageControl how to ActiveTabChanged event after client side event to get data first
ASPxPageControl clientside event ActiveTabChanged
ASPxPageControl - How to set an active tab on the client-side
Hope these help you to implement the functionality as you want to do.

Javascript send innerHTML to server ASP.NET

I have an issue regarding some interaction between Javascript and ASP.net control.
In javascript I get the innerHTML of a content editable like this :
var text = document.getElementById('corps').innerHTML;
document.getElementById('corpsToServer').value = text;
document.getElementById('callingServer').click();
This call an action on a click event for an ASP.NET updatePanel that call the serveur side of my application :
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel runat="server">
<br />
<asp:TextBox CssClass="serveurNeeded" runat="server" ID="corpsToServer" ClientIDMode="Static" ></asp:TextBox>
<br />
<asp:TextBox CssClass="serveurNeeded" ID="recup" runat="server" ClientIDMode="Static">
</asp:TextBox>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="callingProlexis" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
<asp:Button CssClass="serveurNeeded" ID="callingProlexis" runat="server" OnClick="tryReturn"
ClientIDMode="Static" Text="callhim" />
</form>
Then the call is like this :
<script language="C#" type="text/C#" runat="server">
public void tryReturn(object sender, EventArgs e)
{
prolexisIMPL proxy = new prolexisIMPL();
string getCorpsText = corpsToServer.Text;
string retourTest = proxy.tryThis(getCorpsText);
recup.Text = retourTest;
UpdatePanel1.Update();
ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "afterServerReturn();", true);
}
</script>
I have figure that it is the passing of innerHTML that make me get an error 500 from the server. Some post told that it is a validation issue to prevent injection from user side, but configuring the :
ValidateRequest="false"
is a bad idea and does not work.
How can I manage to send my innerHTML to the server side without this error showing up ? Something Like him pretending it's just a string and the tag are just part on the string, not html or javascript injection.
Configuration are ASP.NET MVC 4.0 without code behind, Vanilla Javascript, IE5.
EDIT : the error :
Sys.Webforms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was : 500
You have several solutions :
Encode HTML client side
The cleanest one is to encode your html before sending it to the server. You can do it easy with jQuery, but in javascript you will have to create you own encoding method. You can see an example here : http://www.yuki-onna.co.uk/html/encode.html
Disable Validation
You can disable the server validation, either placing the ValidateRequest="false" in your page header or placing it in the web.config file (very dangerous, because it will be applied on all your website).
This solution is not secure if you store the HTML data for display it in another page, because some users of your application will be able to send dangerous content that will be displayed in the browser of other users.
use encoder.js for encoding html to safe scripts and then send to asp.net. You have to ValidateRequest="false" along with that.
You can get examples here.

AjaxControlToolkit:TabPanel

This control has a property Enabled that acts exactly as Visible behaves i.e. ?.Enabled = false hides the control.
I need to be able to keep all the tabs visible but some to be disabled under code control.
Any hints as to how I can achieve this? Thanks.
Try to set Enabled property for TabPanel.
<ajaxToolkit:TabContainer
ID="TabContainer1" runat="server" ActiveTabIndex="0">
<ajaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="TabPanel1"></ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2"></ajaxToolkit:TabPanel>
<ajaxToolkit:TabPanel ID="TabPanel3" Enabled="False" runat="server" HeaderText="TabPanel3"></ajaxToolkit:TabPanel>
</ajaxToolkit:TabContainer>
Or in code-behind,
TabContainer1.Tabs[0].Enabled = false;
Here is one possible solution using client-side scripting. Basically, handle the OnClientActiveTabChanged event for the TabContainer (which fires whenever the active tab is changed). Then, if the tab is one that you don't want the user to use, change the ActiveTabIndex property of the TabContainer back to one that is acceptable.
Tab Container:
<asp:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="1"
Height="126px" Width="400px" ClientIDMode="Predictable"
onclientactivetabchanged="tabClickCheck" >
<asp:TabPanel ID="TabPanel1" runat="server" HeaderText="TabPanel1">
</asp:TabPanel>
<asp:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2">
</asp:TabPanel>
<asp:TabPanel ID="TabPanel3" runat="server" HeaderText="TabPanel3">
</asp:TabPanel>
</asp:TabContainer>
Javascript handler:
<script type="text/javascript">
function tabClickCheck() {
var tabCont = document.getElementById("<%=TabContainer1.ClientID %>").control;
var tabInd = tabCont.get_activeTabIndex();
tabCont.set_activeTabIndex(2);
}
</script>
This function just sets the ActiveTabIndex to 2, regardless of which tab you clicked (you'll notice I'm also getting the current ActiveTabIndex, but I don't do anything with it - that's just to show you how). Obviously, use whatever logic makes sense for your app =)

Multiple ModalPopupExtenders on one page, each with javascript

Hello all gurus in the area of ASP.NET AJAX and JavaScript!
Here's the deal: I have a user control (ascx) that currently contains a help Button and a ModalPopupExtender showing a Panel. The idea is that the user clicks the button and the help info is presented in a modal popup on top of the page, with another button to close it.
The help info can very well be larger than the window, so I have to resize the modal popup on show. When the control is coded as below, the Panel is resized initially, however; if the parent page has a validation error and is resent to the client, the javascript on top never executes.
Here's the control markup:
<script type="text/javascript">
// Adjust for popup y = 130 and a small gap.
var myAdjustedHeight = getPageHeight() - 150;
if (document.getElementById('<% =pnlPopUp.ClientID %>')) {
document.getElementById('<% =pnlPopUp.ClientID %>').style.height = myAdjustedHeight;
document.getElementById('<% =pnlScroll.ClientID %>').style.height = myAdjustedHeight - 20;
}
</script>
<asp:button id="btnHelp" runat="server" text="Help" />
<asp:updatepanel id="upPopUp" runat="server">
<contenttemplate>
<asp:panel id="pnlPopUp" runat="server" width="600">
<div class="header" style="float: left;">
Help
</div>
<asp:button id="btnClose" runat="server" text="Close" style="float: right; padding-bottom: 3px;" />
<asp:panel id="pnlScroll" runat="server" scrollbars="Vertical" style="clear: both;">
<asp:gridview id="grv" runat="server" autogeneratecolumns="true" showheader="false" gridlines="None" cellspacing="2" cellpadding="2">
</asp:gridview>
</asp:panel>
</asp:panel>
</contenttemplate>
</asp:updatepanel>
<ajaxtoolkit:modalpopupextender id="popUpExtender"
runat="server" backgroundcssclass="modalBackground" okcontrolid="btnClose"
targetcontrolid="btnHelp" popupcontrolid="pnlPopUp" x="100" y="130" />
(The GridView is filled with data in the Page_Load using a predefined DataSet in a basic fashion.)
I have tried to add this:
function pageLoad() {
document.getElementById('<% =popUpExtender.ClientID %>').add_shown(adjustHeight);
}
(where adjustHeight() is a function containing the code from the top) but when it fires I get null back for the ModalPopupExtender - and indeed it never seems to be included into the markup sent down the wire.
BTW, I need to add at least two instances of this help button to present help info for several elements on the page. Hence, I can't use the BehaviorID property of the ModalPopupExtender, since it is piped straight out to the page and I get an id collision.
So, how do I fix this? Am I to move the ModalPopupExtender to the Page or can I solve this within the ascx control?
If anyone has an idea on how to fix this, I would appreciate it.
Use this in your pageLoad:
$find('<% =popUpExtender.ClientID %>');
add_shown wouldn't exist for the HTML element, which document.getElementById returns.

Categories