Sending ASP HiddenField Value through another ASP Control - javascript

I have a asp.net site in which I have two files that need to talk to one another.
Below is a snippet of code from my footer.ascx file. I need to send a string to the MobileAd.ascx.cs file. Below is my relevant code from each file.
I believe everything is set up right I just have no clue how to pass the value properly. The value that is not being sent properly is SendA.value
Here is a snippet from footer.ascx
<%# Register TagPrefix="PSG" TagName="MobileAd" Src="~/MobileAd.ascx" %>
<asp:HiddenField runat="server" ID="SendA" value="" />
<script>
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ||
(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.platform)))
{
document.getElementById('<%=SendA.ClientID%>').value = "mobile";
}
else
{
document.getElementById('<%=SendA.ClientID%>').value = "other";
}
</script>
<div class="bottom" align="center">
<PSG:MobileAd ID="MobileAd" runat="server" AdType = <%=SendA.value%> />
</div>
Here is the receiving end at MobileAd.ascx.cs
private string _AdType;
public string AdType
{
set
{
this._AdType = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
string html = null;
if (!string.IsNullOrEmpty(_AdType))
{
if (_AdType == "mobile")
{
html = "Mobile Ad Code";
}
else
{
html = "Tablet or Desktop Ad Code";
}
divHtml.InnerHtml = html;
}

You are detecting the user-agent with javascript. But, being a server control, the MobileAd.ascx got executed before javascript could execute. You should do it on server-side by checking Request.UserAgent or Request.Browser.IsMobileDevice. If the sole purpose of the property AdType is to just hold user-agent type, you can remove it and try modifying your Page_Load method like this:
protected void Page_Load(object sender, EventArgs e)
{
string html = null;
if (Request.Browser.IsMobileDevice)
{
html = "Mobile Ad Code";
}
else
{
html = "Tablet or Desktop Ad Code";
}
divHtml.InnerHtml = html;
}

Related

How to Pass data from C# server side to htm through webBrowser control?

I am facing a problem passing string to HTML page through javascript.
I have a window form,
A HTML file, where I have my Javascript and HTML code.
In the function in C# page, I have a string that I need to send to the HTML page through javascript. But I can not pass it. Please advise me.
Thanks
My C# method code below
private void Form1_Load(object sender, EventArgs e)
{
Assembly assembly = Assembly.GetExecutingAssembly();
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream("ProjectName.Maps.html"));
webBrowser1.DocumentText = reader.ReadToEnd();
***//pass getDefaultMap() value (str) to the javascript in Maps.html page.***
}
private string getDefaultMap()
{
string str;
str = (#"Exec SP_Map_Display #Opt=1");
return str ;
}
My HTML page is below
<body>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
***// Get the data from C# code str***
}
</script>
<input type="button" name="btnSubmit" value="Submit" />
<div id="dvMap">
</div>
</body>
Assuming this is WinForms since there's a WebBrowser control, to call C# code from the HTML page JavaScript can be accomplished with this minimum example:
Simple HTML page added to the root of the project and Properties was setup to Copy to Output Directory: Copy if newer this will ensure there's a simple page for testing:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebForms WebBrowser Control Client</title>
</head>
<body>
<input type="button" onclick="getLocations()" value="Call C#" />
<script type="text/javascript">
function getLocations() {
var locations = window.external.SendLocations();
alert(locations);
}
</script>
</body>
</html>
The JS function getLocations will call C# method SendLocations, the important parts are the Form1 class annotations and setting webBrowser1.ObjectForScripting = this :
using System.Windows.Forms;
using System.Security.Permissions;
using System.IO;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ObjectForScripting = this;
var path = Path.GetFullPath("Client.html");
var uri = new Uri(path);
webBrowser1.Navigate(uri);
}
public string SendLocations()
{
return "SF, LA, NY";
}
}
Clicking the HTML button Call C# will show a popup with the return value from C# method

WPF Off-Screen WebBrowser Control - Javascript on pageload not working

I am trying to navigate to an aspx using WebBrowser control in wpf. The page has a javascript on onload. Javascript call will work if i place control on a grid an make the visibility of control to collapsed or hidden but I want only off-screen call.
Is there a way to do that or something impossible?
aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function OnloadJSCall() {
window.PageMethods.Docall(onSuccess, onFailure);
}
function onSuccess(result) {
}
function onFailure(error) {
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div><asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<script language="JavaScript"> OnloadJSCall();</script>
</div>
</form>
</body>
</html>
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string Docall()
{
using (var fs = new FileStream("C:\\AD\\Test1111.txt", FileMode.Append, FileAccess.Write))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(System.DateTime.Now);
}
return "Done";
}
}
WPF App
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var webBrowserControl = new WebBrowser();
webBrowserControl.Navigate("http://localhost:53288/WebForm1.aspx");
webBrowserControl.Navigated += webBrowserControlOnNavigated;
}
private void webBrowserControlOnNavigated(object sender, NavigationEventArgs navigationEventArgs)
{
}
}
Ok I got the answer. If no ui component then Javascript won't work. So added the control to a form and it worked!!
var newForm =new Form();
var webBrowserControl = new System.Windows.Forms.WebBrowser();
webBrowserControl.Navigate("http://localhost:53288/WebForm1.aspx");
newForm.Controls.Add(webBrowserControl);

Label id is changing, how to fix this?

I have this asp:label in my page and what I want is to change the text from time to time. But label id is changing from page to page when i run the code. its been appended with "ctl00_bh_" something...
how to fix this?
here are my code snippets.
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "onLoad", "DisplaySessionTimeout()", true);
}
<asp:Label ID="lblSessionTime" runat="server" />
function DisplaySessionTimeout() {
document.getElementById("lblSessionTime").innerHTML = "updating text here";
sessionTimeout = sessionTimeout - 1;
if (sessionTimeout >= 0)
window.setTimeout("DisplaySessionTimeout()", 1000);
else
{
alert("Your current Session is over.");
}
}
thanks
In your Javascript you are trying to access the server side control, you need to use the ClientID, try
document.getElementById("<%= lblSessionTime.ClientID%>").innerHTML ="updating text here";
Or ClientIDMode in aspx page if you are using .Net framework 4 or higher
<asp:Label ID="lblSessionTime" runat="server" ClientIDMode="Static" />

Saving javascript variable in server side variable (vbscript)

I know you cant save javascript variables into server side variables (vbscript) directly, but is there a way around this like saving java script variables into html hidden inputs then using javascript to post. Is this possible? If not what else can i do? Below is my code so far get the value of a drop down list - javascript
function selectedDatabase() {
select_temp = form1.elements["selection"];
select_index = select_temp.selectedIndex;
select_text = select_temp.options[select_index].text;
}
Below is the HTML code
<center><select id="selection" onchange="selectedDatabase()">
<option>Movies</option>
<option>Movies 2</option>
<option>New Movies</option>
<option>New Movies 2</option>
</select></center>
</td></tr>
What you're looking for is called ajax. You can do it manually, or better use a JavaScript library such as MooTools, jQuery, or Prototype.
Check out Google University's Ajax tutorial. I would avoid w3schools' tutorials.
Just to cover all the bases, why can't you just have the user submit the form?
Also, you could do this with cookies, though you won't get the cookie values on the server until the next GET or POST from the user.
It is Possible to store javascript variable values into server side variable. All you have to do is to implement "System.Web.UI.ICallbackEventHandler" class.
Below is the code demonstrating how to do it.
In aspx Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Client Calback Example</title>
<script type="text/ecmascript">
function LookUpStock()
{
var lb=document.getElementById("tbxPassword");
var product=lb.value;
CallServer(product,"");
}
function ReceiveServerData(rValue){
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="password" id="tbxPassword" />
<input type="Button" onclick="LookUpStock">Submit</button>
</div>
</form>
</body>
**
In Code Behind (CS) Page
**
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference
(this,"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
public void RaiseCallbackEvent(String eventArgument)
{
if(eventArgument == null)
{
returnValue = "-1";
}
else
{
returnValue = eventArgument;
}
}
public String GetCallbackResult()
{
return returnValue;
}
}
Now you can get the JavaScript variable "product" value into Server side variable "returnValue".

JavaScript display property

In my form I have a textbox and a calendar along with other controls:
<asp:TextBox ID="TextBox2" runat="server" onfocus="CalOpen()" asp:TextBox>
<asp:Calendar ID="Calendar1" runat="server" style="display:none;"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
<script type="text/javascript">
function CalOpen()
{
var cal = document.getElementById('<%=Calendar1.ClientID%>');
cal.style.display='block';
}
</script>
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox2.Text = Calendar1.SelectedDate.ToLongDateString();
Calendar1.Visible = false;
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.Visible = true;
}
For the first time it worked fine,
but, second time when I click TextBox2, that is, after selecting date for the first time the
browser is throwing error "object required".
I am unable to know where I went wrong.
Please help me in making my code correct.
When you write Calendar1.Visible = false; in server-side code, it doesn't render the calendar at all. Therefore, there is no calendar element for the Javascript to show.
Instead, you should make a CSS class that applies display: none to the calendar, and set the CssClass property to that class on the server.
For example:
<style type="text/css">
.Hidden {
display: none;
}
</style>
<asp:Calendar ID="Calendar1" runat="server" CssClass="Hidden"
onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
TextBox2.Text = Calendar1.SelectedDate.ToLongDateString();
Calendar1.CssClass = "Hidden";
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Calendar1.CssClass = "";
}

Categories

Resources