How can i print the Report without showing the data, that mean just paper output no screen output.
in my Master page i put a iframe:
<iframe id="reportout" width="0" height="0" />
</form>
and in my Ford.aspx:
<script type="text/javascript">
// Submit Button
function OnSumbitButtonClick(s, e) {
// e.processOnServer = false;
var Temp = <%= TempId %> //Get value from Server
//alert(Temp +'--'+ ASPxTextBox_NBR_COLIS.GetValue());
document.getElementById('reportout').contentWindow.location = '../Print/BonEticket_Web.aspx?OdreID=' + Temp + '&CountOrdre=' +ASPxTextBox_NBR_COLIS.GetValue();
}
</script>
<dx:ASPxButton ID="ASPxButton_save" runat="server" Image-Url="~/images/Icon/Good-or-Tick-icon.png" Text="Enregistrer" Width="110px" onclick="ASPxButton_save_Click">
<ClientSideEvents Click ="OnSumbitButtonClick" />
</dx:ASPxButton>
and in m Ford.aspx.cs:
protected void ASPxButton_save_Click(object sender, EventArgs e)
{
try
{
//Get new inserted ID from Database --> my SQL id is autoincrement
TempId = oOrdre_BL.SaveUpdt_Ordre_BL(oPersOrdr, OrdreID);
// Response.Redirect("../Print/BonEticket_Web.aspx?OdreID=" + TempId + "&CountOrdre=" + ASPxTextBox_NBR_COLIS.Text);
}
catch (Exception ex)
{
lbl_err.Text = ex.Message;
if (ex.InnerException != null) { lbl_err.Text += "-->" +ex.InnerException.Message; }
}
The problem here when i enable my javascript: e.processOnServer = false; it work, but i cannot do that because i need the calculated data from Server var Temp = <%= TempId %>
Thanks you in advance for helping me.
Internet Explorer has two events onbeforeprint and onafterprint, they do what they say.
Here's a small tutorial on them: http://www.javascriptkit.com/javatutors/ie5print.shtml
However, if you are outside enterprise environment where everybody are using IE, you'll have to get creative.
An idea I can think of is show the to-print text in a popup window that prints itself and closes.
Related
I am building a web app with C# and asp.net. In the webpage, there is a header with a search bar and a body with a form. When I enter something in the search bar, one of the form fields shows the pop-up, "Please fill out this field".
This field is required, but for the form which has a separate submit button. So what I'm saying is my search button and form are connected but they shouldn't be.
Edit:
Code behind for the search button:
protected void btnOpenModalSearch(object sender, EventArgs e) {
//get information from database to populate the modal box with
PopulateModalBoxGridView();
ScriptManager.RegisterStartupScript(this, this.GetType(), "Properties",
\ "openModal();", true);
}
protected void PopulateModalBoxGridView() {
if (dtSearch == null) return;
//sort the search results in data table
DataView dvSearch = dtSearch.DefaultView;
dvSearch.Sort = SortOrder;
gridSearchResults.DataSource = dvSearch;
gridSearchResults.DataBind();
}
Code behind for the separate form:
protected async void btnCreateNewAsset_Clicked(object objSender, EventArgs evntArgs) {
//create a new asset
//first check for duplicates
if (IsDuplicateAsset()) { return; }
Asset newAsset = new Asset {
//creating asset
};
//post the asset to Team Dynamix
var addAssetUri = new Uri(locationOrigin + webApiBasePath + addAssetPath);
responseMsg = await httpClient.PostAsJsonAsync(addAssetUri, newAsset);
httpResponse = responseMsg.Content.ReadAsStringAsync().Result;
if (!responseMsg.IsSuccessStatusCode) {
Notification.Show(this, "Error. Response content=" + httpResponse, Status.Error);
}
else {
Notification.Show(this, "Successfully Created Asset.", Status.Success);
assetDictionary.Add(serialNumber.Text, serialNumber.Text);
ClearTextFields(frmIndex);
}
}
I found the answer here: HTML 5 required validator triggers on all buttons on the form
To save you the trip, I needed to add formnovalidate="formnovalidate" to my button
<asp:ImageButton ID="BtnSearch" formnovalidate="formnovalidate" data-target="#myModal" ClientIDMode="Static" runat="server" ImageUrl="~/images/search.svg" Text="Search" OnClick="btnOpenModalSearch"></asp:ImageButton>
I'm doing a C# 3-tier project about pets
On load of the first webform I make a query to the database and get the data of all pets (id, name, photo) as a List to be shown as cards with images in HTML, I'm using Materialize by the way, I leave this link as example http://materializecss.com/cards.html
My code behind (Pets.aspx.cs) is this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
NegPet negPet = new NegPet();
StringBuilder sbHtml = new StringBuilder();
List<EntPet> listEntPet = negPet.getAllPet(5); //5 is the user code (get all pets from user 5)
if (listEntPet.Count > 0)
{
foreach (EntPet entPet in listEntPet)
{
sbHtml.Append("<div class=\"col s6 m4\">");
sbHtml.Append("<div class=\"card\">");
sbHtml.Append("<div class=\"card-image\">");
sbHtml.Append("<img src=\"http://www.dogzone.com/images/breeds/beagle.jpg\" alt=\"\" class=\"circle responsive-img\" />");
sbHtml.Append("<asp:LinkButton id=\"lb_"+ entPet.Id_pet + "\" runat=\"server\" CommandArgument='<%# Eval(\""+ entPet.Id_pet + "\") %>')");
sbHtml.Append("\" click=\"updatePet_Click\" class=\"btn-floating halfway-fab waves-effect waves-light red\"><i class=\"material-icons\">edit</i></a>");
sbHtml.Append("</div>");
sbHtml.Append("<div class=\"card-content\">");
sbHtml.Append("<span class=\"card-title\">");
sbHtml.Append(entPet.Name_pet);
sbHtml.Append("</span>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
}
} else
{
sbHtml.Append("<h2>No pets found</h2>");
}
galPet.Controls.Add(new Literal { Text = sbHtml.ToString() });
}
}
Where galPet is a
<asp:PlaceHolder ID="galPet" runat="server" />
This code returns me all the "Id" and "Name" of "Pets" and sets it in the HTML design that I want, similar to a gallery. The problem comes when I try to get to the event onClick="updatePet_Click" apparently it never reaches it's method behind
public void updatePet_Click(Object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument.Substring(3);
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + yourValue + "');", true);
}
What I'm trying to do with this code is retrieve the ID from the clicked asp:LinkButton so I can use it in code behind
I also tried changing the event to "OnClick" but I got this error when tried to click it
Pets.aspx:24 Uncaught ReferenceError: updatePet_Click is not defined
at HTMLUnknownElement.onclick (Pet.aspx:24)
I would like to know how to retrieve the ID to work it in the code behind or if there is another way to pass my list to the HTML design where I can get the clicked ID easier. Thanks
So I've been struggling with this for a couple days now. I have a login page, that checks if the user is logging in for the first time, and if so, it shows a jqueryui Dialog box asking the user to pick their security questions. The Dialog is simple, three dropdowns, three text boxes, and a continue and cancel button. The dialog is displaying find, and when you click continue, the data is saved to the database, but it only saves the default values of the dropdownlists, and it doesnt save the text from the text boxes. It seems to me like the form is posting back before the data saves, and then saves the blank/default content. I've tried everything I can find on the internet to fix this. As of right now, I'm launching the dialog box on page load for testing purposes. Code Below:
Javascript:
function validateQuestions() {
var q1Index = $('#<%= ddlQuest1.ClientID%>').get(0).selectedIndex;
var q2Index = $('#<%= ddlQuest2.ClientID%>').get(0).selectedIndex;
var q3Index = $('#<%= ddlQuest3.ClientID%>').get(0).selectedIndex;
"<%=Q3Index%>" = q3Index;
var label = document.getElementById('<%= _lblQuestError.ClientID%>');
label.style.display = 'none';
if (q1Index == q2Index || q1Index == q3Index || q2Index == q3Index) {label.style.display = 'block';}
else {label.style.display = 'none'}
return false;
}
function validateAnswers() {
var ans1Text = $('#<%= txtAnswer1.ClientID%>').val();
var ans2Text = $('#<%= txtAnswer2.ClientID%>').val();
var ans3Text = $('#<%= txtAnswer3.ClientID%>').val();
var ans1error = document.getElementById('<%= _lblAns1Error.ClientID%>');
var ans2error = document.getElementById('<%= _lblAns2Error.ClientID%>');
var ans3error = document.getElementById('<%= _lblAns3Error.ClientID%>');
ans1error.style.display = 'none';
ans2error.style.display = 'none';
ans3error.style.display = 'none';
if(ans1Text=""){ans1error.style.display = 'block';}
else if(ans2Text=""){ans2error.style.display = 'block';}
else if(ans3Text=""){ans3error.style.display = 'block';}
else { ans1error.style.display = 'none'; ans2error.style.display = 'none'; ans3error.style.display = 'none'}
return false;
}
function cancel() {
$("#_dlgQuest").dialog('close');
return false;
}
function showDialog() {
var secQuestDlg = $('#_dlgQuest').dialog({
bgiframe: true,
height: 350,
width: 900,
modal: true,
overlay: {
backgroundColor: '#000',
opacity: ".8"
}
});
secQuestDlg.parent().appendTo('/html/body/form[0]');
}
Button aspx: <asp:Button ID="_dlgbtnContinue" ToolTip="Continue" runat="server" Text="Continue"
UseSubmitBehavior="false" OnClick="_dlgbtnContinue_Click" CausesValidation="false" />
PageLoad:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlQuest3.Attributes.Add("onchange", "javascript:validateQuestions();");
ddlQuest1.Attributes.Add("onchange", "javascript:validateQuestions();");
ddlQuest2.Attributes.Add("onchange", "javascript:validateQuestions();");
txtAnswer1.Attributes.Add("onblur", "javascript:validateAnswers();");
txtAnswer2.Attributes.Add("onblur", "javascript:validateAnswers();");
txtAnswer3.Attributes.Add("onblur", "javascript:validateAnswers();");
List<String> lstQuestions = QuikDrawServiceHelper._QuikDrawClient.GetQuestions();
ddlCountry.Focus();
FillQuestions();
ClientScript.RegisterStartupScript(GetType(), "hwa", "showDialog()", true);
}
}
Fillquestions:
try
{
foreach (string s in lstQuestions)
{
if (s.Equals(Customer.Quest1Code))
{
q1 = s;
}
if (s.Equals(Customer.Quest2Code))
{
q2 = s;
}
if (s.Equals(Customer.Quest3Code))
{
q3 = s;
}
}
}
catch (Exception ex)
{
}
Complete Click Event:
protected void _dlgbtnContinue_Click(object sender, EventArgs e)
{
Customer = CompanyServiceHelper._CompanyClient.GetCustomerByID(Convert.ToInt32(Session["CustomerID"].ToString()));
if (Session["FirstLogin"] == "Yes")
{
Customer.Quest1Code = ddlQuest1.SelectedValue;
Customer.Quest1Ans = txtAnswer1.Text;
Customer.Quest2Code = ddlQuest2.SelectedValue;
Customer.Quest2Ans = txtAnswer2.Text;
Customer.Quest3Code = ddlQuest3.SelectedValue;
Customer.Quest3Ans = txtAnswer3.Text;
CompanyServiceHelper._CompanyClient.AddQuestionsForCustomer(Customer);
Session["FirstLogin"] = "Yes";
Session["CustID"] = Customer.CustID;
}
I've tried linkbuttons as well, and i get the same thing. Any help would be greatly appreciated.
The root cause of the problem you are facing is the fact that the dialog is made "display:none" when popup disappears, and this resets all the values inside the dialog, making them not accessible on server. Despite "runat=server", form fields are not accessible on server bcz of "display:none", making you think the values are never set !!
Seems like when you click the dlgbtnContinue button it is still not doing a postback, therefore you get the !isPostBack all over, and then resets the values. After this, the _dlgbtnContinue_Click event is getting triggered, saving the blank values. Maybe try to check in !isPostBack if also the values in the DropDown are not the default, meaning that if they are not the default values you do not want to get inside that if again. Just an idea... It would be good to have the _dlgbtnContinue_Click code. Good luck.
I am attempting to provide a web-based solution for users to select a file on shared drives.
I want to use the typical file selector that is provided by windows when you go to browse for a file. The only info I need from this is the full filename + path. Now an obvious solution would be to just have a free-text textbox where users type in their filename, but I am required to use the file selector. (image below)
As a side note I am using the Telerik controls and this download functionality is in a user control that is inside an ajaxified panel in the parent page.
Currently I have this markup:
Add a Link to a Document: <input type="file" id="upLink" runat="server" onchange="LinkSelected(this);" />
<asp:HiddenField ID="hdnLinkFile" runat="server" />
<asp:Button ID="btnLink" runat="server" CssClass="invisiblebutton" OnClick="LinkFile" />
<script>
function LinkSelected(sender) {
if (sender && sender.value.length > 0) {
//save filename to hidden value as it will not otherwise be usable on the server without a postback
$("#<%= hdnLinkFile.ClientID %>").val(sender.value);
//clear
sender.value = null;
//fire server request on this user control
$find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>").ajaxRequestWithTarget("<%= btnLink.UniqueID %>", "");
}
}
</script>
code behind:
protected void LinkFile(object sender, EventArgs e)
{
if (hdnLinkFile.Value.Length > 2 && hdnLinkFile.Value.Substring(0, 2) != #"\\")
{
Code.Common.DisplayMessage("File must be in a shared location!", Page);
}
else
{
//save link string to database
}
}
The purpose of this code is to prevent a full postback. A full postback will cause the file input (upLink) to upload the selected file to the web server. As we are allowing large files (over 100MB) to be linked to, and all I want is the filepath, (and the internet for some of the clients is very slow) there is no need for the upload.
this code works great in IE - unfortunately for inputs with type=file Firefox returns only the filename - not the full path + name . Being that the reason Firefox doesn't provide this data as it is considered a security risk, and also that the client uses firefox by default, I need to find another way. All I want is the full filename + path, without actually uploading the file - how hard can it be???
Well unfortunately the only way I found how to do it was to build my own file selector dialog. Seeing as I am already using the Telerik controls, I used the RadTreeView and RadWindow as below. I've pulled out all the validation to make it simpler. Its based on the Telerik demo here
Explorer.aspx (the popup window)
<script type="text/javascript">
function onNodeClicking(sender, args) {
//fill path textbox
var textbox = document.getElementById('inpPath');
if (args.get_node()._parent._uniqueId == "RadTreeView1")
textbox.value = args.get_node()._properties._data.value; //root node
else
textbox.value = args.get_node()._parent._properties._data.value + "\\" + args.get_node()._getData().text;
}
function onCancel() {
var wnd = getRadWindow();
var openerPage = wnd.BrowserWindow;
openerPage.OnFileSelected('');
wnd.close();
}
function onOK() {
var wnd = getRadWindow();
var openerPage = wnd.BrowserWindow;
openerPage.OnFileSelected(document.getElementById('inpPath').value);
wnd.close();
}
function getRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
</script>
<div id="divFolderPath" style="padding: 0px 0px 10px 10px;">
<input id="inpPath" runat="server" type="text" style="width:80%;" />
<asp:Button ID="btnGo" runat="server" Text="Go" onclick="btnGo_Click" />
</div>
<div id="divButtons" style="padding: 0px 0px 15px 10px; text-align:center;">
<input id="btnOk" type="button" value="OK" onclick="onOK()" style="padding-right:5px;" disabled="disabled" />
<input id="btnCancel" type="button" value="Cancel" onclick="onCancel()" />
</div>
<telerik:RadTreeView ID="RadTreeView1" runat="server"
OnNodeExpand="RadTreeView1_NodeExpand"
OnClientNodeClicking="onNodeClicking">
</telerik:RadTreeView>
Code behind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.UI;
using System.IO;
using Telerik.Web.UI;
//extensions we have pics for
private readonly string[] _knownExtensions = new[] { "csv", "doc", "docx", "gif", "html", "jpg", "pdf", "png", "txt", "xls", "xlsx", "xml" };
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["nodes"] != null && ((List<string>)Session["nodes"]).Count > 0)
{
foreach (string nod in (List<string>)Session["nodes"])
{
AddNode(nod);
}
}
else
{
AddNode(ConfigurationManager.AppSettings["LinkDocumentStartPath"]);
}
}
}
private void AddNode(string rootpath)
{
Directory.GetDirectories(rootpath);
inpPath.Value = rootpath;
//won't get this far if it fails the first check
var dirNode = new RadTreeNode(rootpath)
{
Value = rootpath,
ImageUrl = "~/Content/Images/folder.png",
Expanded = true,
ExpandMode = TreeNodeExpandMode.ServerSideCallBack
};
dirNode.Attributes.Add("isFile", "false");
RadTreeView1.Nodes.Add(dirNode);
}
protected void RadTreeView1_NodeExpand(object sender, RadTreeNodeEventArgs e)
{
BindTreeToDirectory(e.Node.Value, e.Node);
}
private void BindTreeToDirectory(string path, RadTreeNode parentNode)
{
//get directories
string[] directories = Directory.GetDirectories(path);
foreach (string directory in directories)
{
var dirNode = new RadTreeNode(Path.GetFileName(directory))
{
Value = path + "/" + Path.GetFileName(directory),
ImageUrl = "~/Content/Images/folder.png",
ExpandMode = TreeNodeExpandMode.ServerSideCallBack
};
dirNode.Attributes.Add("isFile","false");
parentNode.Nodes.Add(dirNode);
}
//get files in directory
string[] files = Directory.GetFiles(path);
foreach (string file in files)
{
var node = new RadTreeNode(Path.GetFileName(file));
node.Attributes.Add("isFile", "true");
//get extension
string extension = Path.GetExtension(file);
if (!string.IsNullOrEmpty(extension))
{
extension = extension.ToLower().TrimStart('.');
}
//choose an image for the extension
if (Array.IndexOf(_knownExtensions, extension) > -1)
{
node.ImageUrl = "~/Content/Images/" + extension + ".png";
}
else
{
node.ImageUrl = "~/Content/Images/unknown.png";
}
parentNode.Nodes.Add(node);
}
}
//go to a new directory
protected void btnGo_Click(object sender, EventArgs e)
{
string nod = inpPath.Value.Trim();
if (!string.isNullOrEmpty(nod))
{
var nodeslst = new List<string>();
if (Session["nodes"] != null)
{
nodeslst = (List<string>) Session["nodes"];
}
else
{
//session has expired - get nodes from radtree
nodeslst.AddRange(from RadTreeNode rtn in RadTreeView1.Nodes select rtn.Value);
}
if (nodeslst.Contains(nod, StringComparer.OrdinalIgnoreCase) == false)
{
AddNode(nod);
nodeslst.Add(nod);
}
Session["nodes"] = nodeslst;
}
}
and this code goes on the page that has the file select button:
<span style="width:200px; display:inline-block; text-align:right; padding-right:5px;">Add a Link to a Document:</span>
<telerik:RadTextBox ID="txtLinkFileName" runat="server" Width="325px" Enabled="False"></telerik:RadTextBox>
<asp:Button ID="selectFile" OnClientClick="OpenFileExplorerDialog(); return false;" Text="Browse..." runat="server" />
<asp:Button ID="btnLink" runat="server" CssClass="invisiblebutton" OnClick="LinkFile" CausesValidation="false" />
<telerik:RadWindow runat="server" Width="550px" Height="560px" VisibleStatusbar="false"
ShowContentDuringLoad="false" NavigateUrl="Explorer.aspx" ID="ExplorerWindow"
Modal="true" Behaviors="Close,Move,Resize">
</telerik:RadWindow>
<script type="text/javascript">
function OpenFileExplorerDialog() {
var wnd = $find("<%= ExplorerWindow.ClientID %>");
wnd.show();
}
//This function is called from code on the Explorer.aspx page
function OnFileSelected(fileSelected) {
if (fileSelected && fileSelected.length > 0) {
var textbox = $find("<%= txtLinkFileName.ClientID %>");
textbox.set_value(fileSelected);
$find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>").ajaxRequestWithTarget("<%= btnLink.UniqueID %>", "");
}
}
</script>
code behind:
protected void LinkFile(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtLinkFileName.Text))
{
if (txtLinkFileName.Text.Length > 2 && txtLinkFileName.Text.Substring(0, 2) != #"\\")
{
Code.Common.DisplayMessage("File must be in a shared location!", Page);
}
else
{
//just a link to a file - no need to upload anything
//save filepath to database
//filepath = txtLinkFileName.Text;
}
}
}
As you can see it would be a lot easier if smartypants browsers weren't trying to protect us from ourselves, but still accomplishable.
I have inline script such as this, which toggles between an edit and a display divs. If it is inside the the UpdatePanel it requires two click before it works. If I remove the UpdatePanel it works fine with a single click.
Edit
Can anyone help please?
Thanks
EDIT:
Edit function:
function edit(e, id) {
var editdiv = $('#' + id).find('.edit');
var cntdiv = $('#' + id).find('.content');
if (editdiv.css('visibility') == 'hidden') {
editdiv.css('visibility') == 'visible'
cntdiv.css('visibility') == 'hidden'
cntdiv.hide();
editbox.show()
}
else {
editdiv.css('visibility') == 'hidden'
cntdiv.css('visibility') == 'visible'
cntbox.show();
editbox.hide()
}
stopEventBubble(e); // Code to cancel event bubbling;
}
Are you using the ScriptManager to register the edit function?
protected void Page_Load(object sender, EventArgs e)
{
string jsEdit = #"function edit(event, id) {}";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "editFunction", jsEdit);
}
If your code is in an external file, you can register it with the ScriptManager or the ScriptManagerProxy in the aspx for your page:
<ScriptManager runat="server" id="ScriptManager1">
<Scripts>
<asp:ScriptReference path="~/js/edit.js" />
</Scripts>
</asp:ScriptManager>
EDIT:
alright, I know what the issue is now. You aren't setting the css visibility to begin with. So either you need to set the css visibility or you can modify your edit function to follow the following logic:
function edit(e, id) {
var editdiv = $('#' + id).find('.edit');
var cntdiv = $('#' + id).find('.content');
//I reversed it to look for visible instead of hidden. The main problem with this approach and your other approach is that the original value is inherited.
if (editdiv.css('visibility') == 'visible') {
editdiv.css('visibility') == 'hidden'
cntdiv.css('visibility') == 'visible'
cntbox.show();
editbox.hide()
}
else {
editdiv.css('visibility') == 'visible'
cntdiv.css('visibility') == 'hidden'
cntdiv.hide();
editbox.show()
}
stopEventBubble(e); // Code to cancel event bubbling;
}
The other option will require you to set the following in you "edit" and "content" divs.
<div id="edit" style="visibility:hidden"> ... </div>
<div id="content" style="visibility:visible"> ... </div>
If you need further help, I'll need to see your aspx code concerning the UpdatePanel, edit, and content.
Try this:
Edit
Edit
As Chris said:
If you are injecting the function when you click the Edit link the function won't exist the first time you click an Edit link.
What you could do is add the function inside a <script> tag in the <head> section of the markup:
<head>
<script>
function edit(event, id) {
// Your code here
}
</script>
</head>
Or in a separate .js file.