can someone point me to the right direction
I need a code to dynamically create a temporary Web Pop-up Page which I'll declare the HTML Content in ASP.NET Using VB
reason for this function is that I am trying to make Application Form printer and I need to print the current page with the
<script>window.print();</script>
You could generate the entire HTML as string and then use as below:
window.open("data:text/html;charset=utf-8,<head></head><body><h3>Test Document</h3></body><script>window.print();</script>");
Basically,
window.open("data:text/html;charset=utf-8," + YOUR_HTML + "<script>window.print();</script>");
Copy paste the below script in a browser to test:
data:text/html;charset=utf-8,<head></head><body><h3>Test Document</h3></body><script>window.print();</script>
== Updates ==
Aspx.vb Code
Dim htmlText As String = "<head></head><body><h3>Test Document</h3></body>".Normalize()
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "tempWindow", "<script>openTempWindow('" + htmlText + "')</script>", False)
Aspx Code
<script type="text/javascript">
function openTempWindow(content) {
var win = window.open("");
win.document.write(content);
}
</script>
You can achieve that by manipulating the response. This is one way to dinamically create an HTML document. For example:
HttpContext.Current.Response.Write("<html>
<body>
<h1>Something to print</h1>
</body>
<script>window.print();</script>
</html>")
In order to make it a popup window, in your base page you can implement window.open() function after, lets say, a button click. For example:
window.open("../pageReturningDynamicHTML.aspx?someParam=someValue")
In the provided link you can find more examples on how to open a window as popup with settings as sizes and more.
Related
I have a master page that gets all its images from a table on a database, and I am trying to incorporate flash, for banners, but I can't quite seem to figure it out.
Right now there is a:
<asp:image id="headerimg" runat="server">
and that generates the appropriate img tag needed to show an image in html. Now I would like to know if there is any way where I can generate an object tag if a .swf file is present and populate the tag with width height and data and also not show the img tag.
Update__
I now have made a usercontrol that will create the object tag, but can someone please tell me if it is looking like I am doing it right..
IDataReader dr = DB.GetRS("SELECT HeaderGraphic,HeaderAlign, fWidth, fHeight, Flash FROM Store where CustomerID='" + Session["Customer"].ToString() + "'");
if(dr["Flash"] == 1)
{
HtmlGenericControl obj = new HtmlGenericControl("object");
obj.Attributes["width"] = dr["fWidth"];
obj.Attributes["height"] = dr["fHeight"];
obj.Attributes["data"] = dr["HeaderGraphic"];
this.Controls.Add(obj);
}
else
{
HtmlGenericControl image = new HtmlGenericControl("img");
img.Attributes["src"] = dr["HeaderGraphic"];
img.Attributes["align"] = dr["HeaderAlign"];
this.Controls.Add(image);
}
is this continuing to look right? and is there anything I am missing?
Thanks.
Why not create a user control that generates the required <OBJECT /> html to display the swf file and then you can dynamically load these if there are swf file present?
is this looking right? and how do I get this into the html?
Yes it looks right. You can add it into your page this way:
this.Controls.Add(obj);
Hope it helps!
Hanlet
EDIT: I could recommend you to look into Generic Handlers and see if you can somehow use it. Good luck!
I am building a dynamic user control (ascx) which contains a placeholder. Inside the placeholder, there will be n tables. Inside each table, in one of the cells i have the link button as below.
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.NavigateUrl = "javascript:JS_Click();";
I have to call a JS function on the link button click (no postback).
In the JS function, i have to get the id of the control that invoked that JS function. In this case, it will be link button. I am writing the below code in the JS Function:
var ctrl = event.srcElement.id;
but i am getting 'Object Required' error in javaScript.
Few other things: This user control will be loaded in default.aspx page and the JS Function i am writing in default.aspx.
I am not sure why this is not working. I am using IE6/7, VS 2005. Is there any other function or way available to get the srcElement.id. Please help.
Try passing this along when you invoke the method
lnkButton.NavigateUrl = "javascript:JS_Click(this);";
then you can write this in your JS_Click event
function JS_Click(obj)
{
alert("Now I have my object " + obj.id);
}
Another option would be to use jQuery and wire up to the click event on your link buttons.
Add a CssClass attribute to the LinkButton's you are creating:
HyperLink lnkButton = new HyperLink();
lnkButton.ID = "lnkButton_" + ID.ToString();
lnkButton.Text = tstText;
lnkButton.CssClass = "linkButton";
Then write the follwoing JS/ JQuery in your ASPX page:
$(document).ready(function()
{
$('.linkButton', '#userControlID').click(function(e)
{
alert('You clicked linkbutton with ID ' + e.target.id);
});
});
In the above example each link button has class="linkButton" and they are contained within your usercontrol with ID="userControlID".
I need to pass 4 arguments (3 strings and one comma separated list) from an ASP.NET page to another ASP.NET page using jQuery. The destination page ought to be launched as a separate window, which works fine with the following jQuery snippet:
$('#sourcePageBtn').click(function(){
window.open("destinationPage.aspx");
return false;
});
How can I pass the arguments to the destination page? I am trying to avoid the query string to pass the arguments because:
I don't want to show the url arguments (which can also be very long) in the destination window.
There are some special characters like ',/,\, & etc. in the string arguments.
Please suggest.
Edit:
I'm trying to access the arguments in the script section of the aspx file i.e.
<script language="C#" runat="server">
protected void Page_Load ( object src, EventArgs e)
{
//Creating dynamic asp controls here
}
</script>
My specific need for the arguments in the Page_Load of the script section stems from the fact that I am creating a few dynamic Chart controls in the Page_Load which depend on these arguments.
cheers
Initial Thoughts (before solution created)
Use POST for large data instead of GET. With POST no querystring will be used for data and therefore URL length restriction isn't a concern. (The max URL length differs between browsers so you're right to stay away from it when large data is moving).
Special URL characters can be encoded to be passed in the query string so that shouldn't be an issue.
Alternatively you might store the data on the server side from the first page, and have the second page pick it up from the server side. But this is overkill. And it makes you do unneeded server programming.
Passing state via HTTP calls is standard practice. You shouldn't try to circumvent it. Work with it. All the facilities are built in for you. Now it's just up to jQuery to provide us some help...
Note: Be careful using jQuery for main app features in case JavaScript is disabled in the browser. In most cases your web application should be usable at a basic level even when JavaScript is disabled. After that's working, layer on JavaScript/jQuery to make the experience even better, even awesome.
Edit: Solution (with ASP.NET processing)
Key resources for solution implementation are:
How use POST from jQuery - initiates the request, passes arguments, gets response
jQuery context argument - this is how the popup window DOM is accessed/affected from the main window
How it works: From a main page, a POST occurs and results are displayed in a popup window. It happens in this order:
The main script opens a popup window (if it doesn't already exist)
main script waits for popup window to fully initialize
main script POSTs (using AJAX) arguments to another page (sends a request)
main script receives response and displays it in the popup window.
Effectively we have posted data to a popup window and passed arguments to the processing.
Three pages follow and they constitute the complete solution. I had all 3 sitting on my desktop and it works in Google Chrome stable version 3.0.195.38. Other browsers untested. You'll also need jquery-1.3.2.js sitting in the same folder.
main_page.html
This is the expansion of the logic you provided. Sample uses a link instead of a form button, but it has the same id=sourcePageBtn.
This sample passes two key/value pairs when the POST occurs (just for example). You will pass key/value pairs of your choice in this place.
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
</head>
<body>
<a id="sourcePageBtn" href="javascript:void(0);">click to launch popup window</a>
<script>
$(function() {
$('#sourcePageBtn').click( function() {
// Open popup window if not already open, and store its handle into jQuery data.
($(window).data('popup') && !$(window).data('popup').closed)
|| $(window).data('popup', window.open('popup.html','MyPopupWin'));
// Reference the popup window handle.
var wndPop = $(window).data('popup');
// Waits until popup is loaded and ready, then starts using it
(waitAndPost = function() {
// If popup not loaded, Wait for 200 more milliseconds before retrying
if (!wndPop || !wndPop['ready'])
setTimeout(waitAndPost, 200);
else {
// Logic to post (pass args) and display result in popup window...
// POST args name=John, time=2pm to the process.aspx page...
$.post('process.aspx', { name: "John", time: "2pm" }, function(data) {
// and display the response in the popup window <P> element.
$('p',wndPop.document).html(data);
});
}
})(); //First call to the waitAndPost() function.
});
});
</script>
</body>
</html>
popup.html
This is the popup window that is targeted from the main page. You'll see a reference to popup.html in the jQuery script back in the main page.
There's a "trick" here to set window['ready'] = true when the popup window DOM is finally loaded. The main script keeps checking and waiting until this popup is ready.
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
</head>
<body>
<!-- The example P element to display HTTP response inside -->
<p>page is loaded</p>
</body>
<script>
$(function() {
window['ready'] = true;
});
</script>
</html>
process.aspx.cs (C# - ASP.NET process.aspx page)
The dynamic server page the arguments are POSTed to by the main page script.
The AJAX arguments arrive in the Page.Request collection.
The output is delivered back as plain text for this example, but you can customize the response for your apps requirements.
public partial class process : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
// Access "name" argument.
string strName = Request["name"] ?? "(no name)";
// Access "time" argument.
string strTime = Request["time"] ?? "(no time)";
Response.ContentType = "text/plain";
Response.Write(string.Format("{0} arrives at {1}", strName, strTime));
}
protected override void Render(System.Web.UI.HtmlTextWriter writer) {
// Just to suppress Page from outputting extraneous HTML tags.
//base.Render(writer); //don't run.
}
}
Results of this are displayed into the popup window by the original/main page.
So the contents of the popup window are overwritten with "[name] arrives at [time]"
Main References: HTTP Made Really Easy, jQuery Ajax members and examples.
If you keep a reference to the new window when you open it, ie var destWin = window.open(...) then you can access the variables and methods on the destWin window object. Alternatively you can "reach back" from the destination window with window.opener.
The scenario...I have a list of dynamic hyperlink controls on an ajax panel that link directly to a WORD doc located on a share. Clicking any link opens WORD client side (I set the file association to do that so the IE browser doesn't try to open it instead).
LinkButtons won't work because it doesn't do a direct link to the doc from the browser and I don't want server automation or activex, since I want each client to open the doc using their own box as if they had simply clicked on the document itself.
But I need to change an image in an image control once they've clicked on the hyperlink. In other words, I need the link to sit on top of a control that does cause a postback so I can get at the posting controls ID and do my thing. I'm also trying to avoid client side scripting though I'm sure there may be a convoluted way to do that.
Here is the code in the loop that creates the dynamic link. I started with just the hyperlink control, then this code is messing with adding a hyperlink to a label, that's why it's showing as it is:
Label lblWordLink = new Label();
HyperLink hrefLetter = new HyperLink();
hrefLetter.Text = items.letterName;
hrefLetter.NavigateUrl = folderForPackageLetters + items.letterName + wordDocExtension;
hrefLetter.ID = "standardLettersHref_" + items.letterName;
lblWordLink.Text = "<a href='" + hrefLetter.NavigateUrl.ToString() + "'>" + items.letterName + "</a>" ;
tRow.Cells[1].Controls.Add(lblWordLink);
I'm looking for a way to let the link open the doc and at the same time postback. Is there a way to layer the link control on top of another control such that the link just links and the control beneath causes a postback?
32U
Fixed: the answer gave the clue. On the server, during dynamic control creation I did:
HyperLink hrefLetter = new HyperLink();
hrefLetter.ID = "standardLettersHref_" + items.letterName;
hrefLetter.Text = items.letterName;
hrefLetter.NavigateUrl = folderForPackageLetters + items.letterName + wordDocExtension;
hrefLetter.Attributes.Add("OnClick", "letterHrefClick('" + items.letterName + wordDocExtension + "')");
tRow.Cells[1].Controls.Add(hrefLetter);
then client side I pushed a value into a hidden control inside the ajax panel when the hyperlink control was clicked and forced submit:
function letterHrefClick(link) {
//alert(link);
form1.hdnLetterClick.value = link;
form1.submit();
}
After the submit, back on server side, I got the value in the Page_Load event:
string x = hdnLetterClick.Value;
nice!
update...
An even better way to do this... in the javascript postback use:
__doPostBack("hdnLetterClick", "somevalue");
then in the codebehind in the Page_Init you can do (not for button or imgbutton):
string postbackControlID = Request.Params.Get("__EVENTTARGET");
string postbackArgument = Request.Params.Get"__EVENTARGUMENT");
to get at what you need. This is better if dealing with dynamic controls so you can control state during control recreation.
If you give your link an onclick attribute, those javascript actions should also be executed when the link is selected.
I have an ASP.NET user control (.ascx file). In this user control I want to use a .js file.
So I include <script src="file.js" type"text/javascript"></script> on the page.
However, sometimes I use this user control in a webpage where this same script has already been loaded.
How can I add a <script /> declaration that will render on the page only if the page doesn't already contain another <script /> tag for the same script?
As you are using asp.net, it makes sense to do the check server-side as that will be where you choose to add the reference to the javascript file. From your .ascx file you could register with the following:
this.Page.ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
... from your page you just call the ClientScript object directly:
ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
The 'GlobalUniqueKey' can be any string (I use the url of the javascript file for this too)
If you try to register a script with the same key string, it doesn't do anything. So if you call this in your page, your control or anywhere else, you'll end up with only one reference in your page. The benefit of this is that you can have multiple instances of a control on a page and even though they all try to register the same script, it is only ever done a maximum of one time. And none of them need to worry about the script being already registered.
There is a 'IsClientScriptIncludeRegistered(stringkey)' method which you can use to see if a script has already been included under that key but it seems pretty redundant to do that check before registering as multiple attempts to register do not throw exceptions or cause any other errors.
Doing the check client-side means that, assuming the multiple javascript references are cached by the browser (they may not be), you still have multiple tags and the over head of each one causing some javascript to run. If you had 20 instances of your control on a page, you could get serious issues.
You can do one of two things client side...
Check the dom for the script tag corresponding to the javascript file your want to check
Test a variable or function you know has/will be defined within the javascript file for undefined.
Here's a quick JS function which uses JQuery to do what you need:
function requireOnce(url) {
if (!$("script[src='" + url + "']").length) {
$('head').append("<script type='text/javascript' src='" + url + "'></script>");
}
}
use something like the following:
if(typeof myObjectOrFunctionDecalredInThisScript != 'undefined') {
// code goes here
var myObjectOrFunctionDecalredInThisScript = { };
}
This tests if your object or function already exists and thus prevents redeclaration.
var storePath = [];
function include(path){
if(!storePath[path]){
storePath[path]= true;
var e = document.createElement("script");
e.src = path;
e.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
return false;
} }
use this in your main page and call function include with argument javascript file name
As you want to include javascript on one page of your site only.
If you use Asp.net(4.0) then it is very easy.
Just include following code
<script type="text/javascript" scr="filepath and name here"></script>
in ContentPlaceHolder of content page.
#Shimmy I am coming across this after a long while but maybe it might still be useful or at least help other coming from behind. To check if jquery is already loaded do this
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.x.x.min.js"><\/script>')</script>
Don't miss the escape character in the closing script tag in document.write statement.
#mysomic, why did I not think of that. thumbs up
PS: I would have loved to write this right under the line where #Shimmy wrote that jQuery itself is the script he wants to load. But dont know how to write it there. cant see a reply or anything similar link. This may sound dumb but maybe I'm missing something. Pls point it out, anybody?
If you need it from server side, and Page.ClientScript.RegisterClientScriptInclude won't work for you in case script was included by some other way other then Page.ClientScript.RegisterClientScript (for example page.Header.Controls.Add(..), you can use something like this:
static public void AddJsFileToHeadIfNotExists(Page page, string jsRelativePath)
{
foreach (Control ctrl in page.Header.Controls)
{
if (ctrl is HtmlLink htmlLink)
{
if (htmlLink.Href.ToLower().Contains(jsRelativePath.ToLower())) return;
}
if (ctrl is ITextControl textControl
&& (textControl is LiteralControl || textControl is Literal))
{
if (textControl.Text.ToLower().Contains(jsRelativePath.ToLower())) return;
}
if (ctrl is HtmlControl htmlControl)
{
if (htmlControl.Attributes["src"]?.ToUpper()
.Contains(jsRelativePath.ToUpper())) return;
}
}
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", page.ResolveUrl(jsRelativePath));
page.Header.Controls.Add(Include);
}