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

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);

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

how to pass value from javascript to ASP control

Good day,
Been new to web development (i use ASP.NET) and i had this goal of passing/returning a value to display on HTML element such such as input. I had done searching and trying most of the solutions i found but none work, the output still returns an empty value on the HTML input. why is that? my code i'm working on can be seen below:
javacript:
function confirmExistence(entityValue) {
var entity = "Staff";
var result = "";
if (entityValue === '0') {
entity = "Student";
}
if (confirm(entity + " w/ same name is already registered. is this a different " + entity + "?")) {
result = "Yes";
} else {
result = "No";
}
alert(result);
document.getElementById('<%= fieldFirstNameStudent.ClientID %>').value = result;
}
html:
<asp:button class="by-button" id="btnStudentEnc" runat="server" text="Encode" OnClick="btnStudentEnc_Click" />
<asp:textbox type="text" class="mfield" placeholder="First Name" id="fieldFirstNameStudent" runat="server" />
asp c#:
protected void btnStudentEnc_Click(object sender, EventArgs e)
{ **some sql database condition here to run the clientscript below**
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true); }
Result is as follows on this image:
UPDATE: IF ABOVE IS TOO COMPLICATED. i created a new web form having simple block of codes that still doesn't work
Aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="LobbyStudents.aspx.cs" Inherits="LobbyStudents" %>
<asp:Content ID="Content0" ContentPlaceHolderID="title" Runat="Server">
LobbyStudents
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:textbox placeholder="First Name" id="fieldFirstNameStudent" runat="server"/>
<asp:button runat="server" text="Encode" OnClick="btnStudentEnc_Click"></asp:button>
</asp:Content>
Aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class LobbyStudents : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnStudentEnc_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"studentConfirmExistence", "confirmExistence('0');", true);
}
}
ClientScript works and even does the alert box. Still textbox is still empty and doesn't contain "whatswrong?" value
unlike i try it on this one:
<!DOCTYPE html>
<html>
<body>
Name: <input type="text" id="myText" value="tch">
<p>Click the button to change the value of the text field.</p>
<button onclick="confirmExistence('0')">Try it</button>
<script>
function confirmExistence(entityValue) {
alert(entityValue);
document.getElementById("myText").value = "whatswrong?";
}
</script>
</body>
</html>
where it works.
What's the difference between the two and why it doesn't happen on asp controls
ok, figure out what is the issue for your first example, is not related to the position, but
change your
document.getElementById("<%= fieldFirstNameStudent %>").value = "whatswrong?";
to
document.getElementById("<%= fieldFirstNameStudent.ClientID %>").value = "whatswrong?";
this will generated in html as
document.getElementById("System.Web.UI.WebControls.TextBox").value = "whatswrong?";
which the js not able to find the control name as System.Web.UI.WebControls.TextBox
if assign with .ClientID, it will generate the correct id
document.getElementById("MainContent_fieldFirstNameStudent").value = "whatswrong?";

Sending ASP HiddenField Value through another ASP Control

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;
}

ASP.Net printing without dialog box

I want my web application to print w popup page just after appearance automatically without asking the client to choose with printer to be choose.
how can I handle silent printing in ASP.Net with java-script or ajax or what is the most suitable solution for this case?
You can't and for good reasons, such as:
The user should always be able to choose which printer they want to use.
The user should always be able to choose whether they print something or not (imagine the spam that would constantly fly out of your printer otherwise)
Some third party controls are available for this(in WPF). Please check whether this is useful in asp.net also.
http://www.textcontrol.com/en_US/support/documentation/dotnet/n_wpf_printing.printing.htm
//OnTouchPrint.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Printing;
using System.IO;
using System.Drawing;
namespace TokenPrint
{
public partial class Try : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
SolidBrush Brush = new SolidBrush(Color.Black);
string printText = TextBox1.Text;
g.DrawString(printText, new Font("arial", 12), Brush, 10, 10);
}
protected void Press_Click(object sender, EventArgs e)
{
try
{
string Time = DateTime.Now.ToString("yymmddHHMM");
System.Drawing.Printing.PrinterSettings ps = new System.Drawing.Printing.PrinterSettings();
ps.PrintToFile = true;
// ps.PrintFileName = "D:\\PRINT\\Print_"+Time+".oxps"; /* you can save file here */
System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
System.Drawing.Printing.StandardPrintController printControl = new System.Drawing.Printing.StandardPrintController();
pd.PrintController = printControl;
pd.DefaultPageSettings.Landscape = true;
pd.PrinterSettings = ps;
pd.Print();
TextBox1.Text = "";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Printed Successfully.Check: Drive D')", true);
}
catch (Exception ex)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Try.aspx");
}
}
}
//OnTouchPrint.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OnTouchPrint.aspx.cs" Inherits="TokenPrint.Try" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" Width="235px" Height="142px"
TextMode="MultiLine"></asp:TextBox>
<br />
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Empty message can not be printed!"
ValidationGroup="vgp1"></asp:RequiredFieldValidator>
<br />
<br />
<asp:Button ID="Press" runat="server" Text="Press" onclick="Press_Click"
ValidationGroup="vgp1" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Refresh"
ValidationGroup="vgp2" />
</form>
</body>
</html>

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