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>
Related
I am trying to use a c# variable to remove an attribute.
I am testing my approach before actually coding application.
I've tried javascript and jQuery but found nothing that would allow to
substitute TextBox ID with value of string in codebehind.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="WebApplication2.index" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="myText" runat="server" required="required"></asp:TextBox>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string straspID = "myText";
bool fieldRequired = false;
if (fieldRequired == false)
{
//FindControl("myText");
FindControl(straspID);
if (straspID != null)
//
myText.Attributes.Remove("required");
// I want to use straspID instead of the ID of the asp page
// which will returned from a table - I'm simulating here
// I get an error if I use straspID for remove attribute
}
}
}
}
My expected result is to remove the attribute for selected ID.
I am currently getting a syntax error.
This
FindControl(straspID);
is not doing what you think it is.
Can you check your index.aspx.designer.cs file and see if there is a protected member variable called 'myText' ?
If there is, you can simply do this: -
if (fieldRequired == false)
{
myText.Attributes.Remove("required");
}
If there is no protected member called myText, add one at class level to 'index': -
namespace WebApplication2
{
public partial class index : System.Web.UI.Page
{
protected Textbox myText;
(etc)
As long as you declare it of the correct type and with the same name and casing, there is no need to resort to FindControl to access a server control.
private void loadform(List providerList)
{
foreach (ProviderInRequest req in providerList)
{
// taget div for plan
Control ctrl = FindControl("div" + req.aspName);
// set visible to true if we found it.
if (ctrl != null)
{
//set div to visible
ctrl.Visible = true;
// set label to proper text
Label lbl = (Label)Page.FindControl("lbl" + req.aspName);
lbl.Text = displayName;
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?";
I've been struggling for a while with a Javascript/C# issue i have. I've been trying to set a Session variable from Javascript. I tried to use page methods before but it resulted in my javascript crashing.
In the javascript :
PageMethods.SetSession(id_Txt, onSuccess);
And this page method :
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
Page aPage = new Page();
aPage.Session["id"] = value;
return value;
}
I haven't had any success with this. Therefore, i tried to set the value of a textbox from my javascript and put a OnTextChanged event in my c# to set the session variable but the event is not fired.
In the javascript:
document.getElementById('spanID').value = id_Txt;
In the html :
<asp:TextBox type="text" id="spanID" AutoPostBack="true" runat="server"
ClientIDMode="Static" OnTextChanged="spanID_TextChanged"
style="visibility:hidden;"></asp:TextBox>
In the cs :
protected void spanID_TextChanged(object sender, EventArgs e)
{
int projectID = Int32.Parse(dropdownProjects.SelectedValue);
Session["id"] = projetID;
}
Does anyone have an idea as of why none of my events where fired ? Do you have an alternative solution that I could try ?
I found the issue, I didn't have the enableSession = true and i had to use the HttpContext.Current.Session["id"] = value, like stated by mshsayem. Now my event is fired properly and the session variable is set.
First, ensure you have sessionState enabled (web.config):
<sessionState mode="InProc" timeout="10"/>
Second, ensure you have page-methods enabled:
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Third, set session value like this (as the method is a static one):
HttpContext.Current.Session["my_sessionValue"] = value;
Sample aspx:
<head>
<script type="text/javascript">
function setSessionValue() {
PageMethods.SetSession("boss");
}
</script>
</head>
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<asp:Button ID="btnSetSession" Text="Set Session Value (js)" runat="server" OnClientClick="setSessionValue();" />
<asp:Button ID="btnGetSession" Text="Get Session Value" runat="server" OnClick="ShowSessionValue" />
<br/>
<asp:Label ID="lblSessionText" runat="server" />
Sample code behind:
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
HttpContext.Current.Session["my_sessionValue"] = value;
return value;
}
protected void ShowSessionValue(object sender, EventArgs e)
{
lblSessionText.Text = Session["my_sessionValue"] as string;
}
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);
I want to display a date with the culture "he-IL" and the Hebrew calendar, but I have not had any success. I'm getting the following:
Expected:
יום שלישי ט"ז אייר תשע"ב
Actual:
יום שלישי 08 שבט 2012
Just one part of the date is being dispalyed correctly, any ideas why is this happening? Here is one example using C# (It displays the date correctly) and another with Javascript (it does not display the date correctly):
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent" >
<script type="text/javascript">
function foo() {
var d = new Date();
var p = document.getElementById("txtHebrewDateJS");
p.value = d.localeFormat(Sys.CultureInfo.CurrentCulture.dateTimeFormat.LongDatePattern);
}
</script>
<asp:Label runat="server" Text="Hebrew calendar, culture he-IL, using code behind" />
<asp:TextBox runat="server" ID="txtHebrewDate" />
<br />
<asp:Label ID="Label1" runat="server" Text="Hebrew calendar, culture he-IL, using asp net ajax" />
<asp:TextBox runat="server" ClientIDMode="Static" ID="txtHebrewDateJS" />
<br />
<asp:Button runat="server" Text="load hebrew date" onclientclick="foo();" />
Code behind:
using System;
using System.Globalization;
using System.Threading;
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
txtHebrewDate.Text = DateTime.Now.ToString(Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern);
}
protected override void InitializeCulture() {
var c = new System.Globalization.CultureInfo("he-IL");
c.DateTimeFormat.Calendar = new HebrewCalendar();
Thread.CurrentThread.CurrentCulture = c;
Thread.CurrentThread.CurrentUICulture = c;
base.InitializeCulture();
}
}
public string HebrewDate(string dateString)
{
DateTime date = DateTime.Parse(dateString);
var ci = CultureInfo.CreateSpecificCulture("he-IL");
ci.DateTimeFormat.Calendar = new HebrewCalendar();
return date.ToString("D", ci);
}
If you don't want to display the day of week, You can change line:
return date.ToString("D", ci);
into:
return date.ToString("d", ci);
Source: Shimmy's comment on C# and iOS Programming blog