I have a web page where it will input an excel/CSV file from the user and read the data from it and import to DB.While inserting each record.I just want to show the details about the record being inserted to the user.(Ex : Client Details of A is adding...)
Try this... Set the output to unbuffered (Response.BufferOutput), and include some javascript in your page that updates the UI as you see appropriate. For example, it might update a SPAN with a percentage complete or the details of the record you are processing. Then in your server code, output <script> tags that call the Javascript function from the Render override. Make sure you call Flush() at the appropriate times, and also Flush the base code after it Renders... The JS function calls should get sent down at the appropriate times and executed on the client, resulting in an updating page.
For example... Your HTML page might look like this:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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>
<script type="text/javascript">
function UpdateScreen(t) {
document.getElementById('output').innerHTML = t;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id='output'></div>
</div>
</form>
</body>
</html>
<script type="text/javascript">
UpdateScreen('hello');
</script>
and your codebehind will look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void Render(HtmlTextWriter writer)
{
Response.BufferOutput = false;
base.Render(writer);
Response.Flush();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
Response.Write(string.Format("<script type='text/javascript'>UpdateScreen('{0}');</script>", i * 10));
Response.Flush();
}
}
}
}
I know this is an old question, and the owner of it may have moved on a long time ago. Anyway:
The proposed solution will not work on ASP.NET MVC. And if you ask me, which you don't, I'll say this is not the cleanest solution to the problem:
Here's a jQuery one,
And here's an IFrame one.
Related
I tried something by mistake and i do not understand why this is working:
I've created 2 asp.net web forms called page1.aspx and page2.aspx
On page1.aspx:
In code behind i declare a static string: field1.
I put a simple button.
When I click on this button:
field1="Hello world"
Response.Redirect("page2.aspx")
On page2.aspx, in Page_load, i display page1.field1 value.
When page2.aspx is loaded, page1.aspx should not be loaded in memory. I do not understand why page1.field1 still contains "Hello world value !"
Can anyone explain me why this code works ? Is it a good thing to work this way ?
Does asp store static fields in viewstate or session ?
Thanks
Here is page1.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page1.aspx.cs" Inherits="WebApplication7.page1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Here is page1.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class page1 : System.Web.UI.Page
{
public static string field1;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
field1 = "Hello world";
Response.Redirect("page2.aspx");
}
}
}
Here is page2.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication7
{
public partial class page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(page1.field1);
}
}
}
The keyword "static" means that only one instance of a given variable exists for a class. Static variables are used to define constants because their values can be retrieved by invoking the class without creating an instance of it.
Static variables can be initialized outside the member function or class definition.
Note
Unlike other member variables, only one copy of the static variable exists in memory for all the objects of that class. Therefore, all objects share one copy of the static variable in memory.
In your situation, you had set field1 = "Hello World" in Page1 and on button click you will be redirected on Page2 and write that field1 variable on your page which is the static variable of your Page1 class.
Once you make a field static, it will be in memory till app pool is recycled(full application memory is recycled). I don't know what you are trying, but declaring a static field in a code behind pages is not a good idea.
<script runat="server">
Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' The first time the page loads,
' render the DefaultView.
If Not IsPostBack Then
' Set DefaultView as the active view.
MultiView1.SetActiveView(DefaultView)
End If
End Sub
Sub LinkButton_Command(sender As Object, e As System.Web.UI.WebControls.CommandEventArgs)
' Determine which link button was clicked
' and set the active view to
' the view selected by the user.
Select Case (e.CommandArgument)
Case "DefaultView"
MultiView1.SetActiveView(DefaultView)
Case "News"
MultiView1.SetActiveView(NewsView)
Case "Shopping"
MultiView1.SetActiveView(ShoppingView)
Case Else
Throw New Exception("You did not select a valid list item.")
End Select
End Sub
</script>
what is difference between above code in(aspx) And if the same code in code behind(aspx.cs). Difference between function defined in tag with runat="server" attribute and function defined in code behind...?
How to execute JavaScript Function From ASP.NET Code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="How_calljavascript_aspx_page.aspx.cs" Inherits="How_calljavascript_aspx_page" %>
<!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>Call JavaScript in asp.net page by C# on page load </title>
<script type="text/javascript">
function MyFunction() {
alert('this is javascript function run by C# code.');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
execute JavaScript from code behind in asp.net:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class How_calljavascript_aspx_page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"alert", "MyFunction();", true);
}
}
}
Functionally there is no difference between these two approaches, both will work the same for you.
Page script is useful if you have a small server side code, so that you can embed that code in the page itself.
But this will make things messier if the code is large.
The page designers will have access to the page code here.
The code behind approach provides you a clear separation of HTML and asp or VB code. Thats all...no functional difference between two approaches.
I can't find a way to pass a variable declared in my code-behind aspx.js file to the corresponding code-behind.aspx markup file. The error I keep getting is this:
Parser Error Message: Code blocks are not allowed in this file.
My Code-Behind.aspx.js looks like this:
import System;
package Test {
class CodeBehind extends System.Web.UI.Page {
public var my_var;
public function Page_Load(sender, E:System.EventArgs) {
my_var = "This is my_var.";
}
}
}
I compile the code-behind file manually like this:
jsc.exe /t:library /out:bin\codebehind.dll codebehind.aspx.js
The Code-Behind.aspx looks like this:
<%# Page Language="JScript" Inherits="Test.CodeBehind" CompilationMode="Never" %>
<HTML>
<HEAD>
<TITLE>Hello World Test</TITLE>
</HEAD>
<BODY STYLE="font-size:12;font-family:arial,verdana,sans-serif;">
<FORM RUNAT="server">
<%= my_var %>
</FORM>
</BODY>
</HTML>
I know there are ASP.NET server controls such as asp:label and all that stuff but all I want is print out the contents of simple variables which serve as placeholders.
I don't want the website to compile everytime it is requested and I would like to keep the CompilationMode option set to "Never" and compile all code manually if possible.
Thanks!
Codebehind
protected string my_var { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
my_var = "Hello";
}
html
<%= my_var %>
I am trying to display an image from my database. I have an generic handler to display the image. But my problem is that it doesn't get called. My code for calling the handler is
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
where id is a number and ShowImage.ashx is the handler. The breakpoints in .ashx file doesn't get hit either. I am new to asp.net. So any help would be highly appreciated.
In this cases the steps that you need to follow is to see how the html is rendered.
So, right click on the html page, and "view page source".
There locate the point that the ShowImage.ashx is called, and see if the full rendered path is correct.
From there you simple correct the path.
Additional you can use the browser tools to see what browser looks for, and if he finds it or not. On google chrome for example you make right click, then inspect elements and then click on the network. There you can see with red, what files your page can not find, and you need to fix the path.
Check this sample Example code this might help you.
ASPX Code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
HTTP Handler class Impliment in Img tag
</h1>
<h1>Id : 1</h1>
<img src="ImageHandler.ashx?id=1" alt="Dynamic Image" />
<h1>Id : 2</h1>
<img src="ImageHandler.ashx?id=2" alt="Dynamic Image" />
</div>
</form>
</body>
</html>
C# Examples (ImageHandler.ashx File) :
<%# WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
context.Response.ContentType = "image/jpeg";
if (context.Request.QueryString["id"] == "1")
{
context.Response.WriteFile("bamboo.jpg");
}
else
{
context.Response.WriteFile("palmtree.jpg");
}
}
public bool IsReusable {
get {
return false;
}
}
}
Here is live downloadable C# Examples and VB.Net Examples of this. Click Here...
Setting the src attribute of an IFrame to data:application/pdf;base64, isn't working for me, any ideas why?
Here's the .aspx markup
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function loadIFrameFromHiddenField()
{
//get the node containing the base64 pdf data from the xml in the hidden field
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.loadXML(document.getElementById("pdfData").value);
xmlDoc.setProperty('SelectionLanguage', 'XPath');
var pdfDataNode = xmlDoc.selectSingleNode("//PDF");
//if we've got the node
if (pdfDataNode != null)
{
//get the data and append it to the src contents
var pdfIFrameSrc = "data:application/pdf;base64," + pdfDataNode.text;
//set the src attribute
document.getElementById("pdfIFrame").setAttribute("src", pdfIFrameSrc);
}
}
</script>
</head>
<body>
<form id="form1" runat="server" style="width:100%;height:100%;">
<asp:HiddenField ID="pdfData" runat="server" />
<div style="width:100%;height:80%;">
<iframe id="pdfIFrame" runat="server" scrolling="auto" frameborder="0" marginheight="0" marginwidth="0" style="height:99.5%;width:99.5%" />
</div>
</form>
</body>
</html>
and here's the code behind:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//get the bytes from our PDF
Byte[] pdfBytes = File.ReadAllBytes("c:\\temp\\Test.pdf");
//build xml containiing our base64 encoded pdf data and put it in hidden field
pdfData.Value = buildDocumentXML(pdfBytes, "TestDoc");
//call js function to add the src to the iframe
String scriptText = "<script type='text/javascript'>loadIFrameFromHiddenField()</script>";
ClientScript.RegisterStartupScript(this.GetType(), "loadIFrameFromHiddenField", scriptText);
}
private string buildDocumentXML(Byte[] pdfBytes, string documentName)
{
StringBuilder documentsString = new StringBuilder();
XmlWriterSettings documentsXmlSettings = new XmlWriterSettings();
documentsXmlSettings.Indent = false;
documentsXmlSettings.OmitXmlDeclaration = true;
documentsXmlSettings.ConformanceLevel = ConformanceLevel.Fragment;
documentsXmlSettings.NewLineHandling = NewLineHandling.None;
using (XmlWriter documentsXmlWriter = XmlWriter.Create(documentsString, documentsXmlSettings))
{
documentsXmlWriter.WriteStartElement("DOCUMENTS");
documentsXmlWriter.WriteStartElement("FILENAME");
documentsXmlWriter.WriteString(documentName);
documentsXmlWriter.WriteEndElement();
documentsXmlWriter.WriteStartElement("PDF");
documentsXmlWriter.WriteBase64(pdfBytes, 0, pdfBytes.Length);
documentsXmlWriter.WriteEndElement();
documentsXmlWriter.WriteEndElement();
}
return documentsString.ToString();
}
}
I should say unlike in this example, in the real app, the pdf data is generated serverside. The reason I'm trying to load the pdf data clientside is I have to have the pdf byte data clientside anyway to do something else with and I'm trying to reduce instances of this data being generated and chucked around.
Just stick the above code and markup into a simple one page website in VS2005 and stick any old pdf in c:\temp\, call it TestDoc.pdf and it should compile and run.
Basically the behaviour I'm getting is nothing in the iframe at all.
I'm using IE7 so that might be a problem. I don't know since there's precious little information about using the data:application/pdf;base64[base64 data] syntax around.
It may be tacky to reference wikipedia, but Wikipdia says that there may be some restrictions on which filestypes you are allowed to use the data:filetype;base64 syntax on. Namely, only pictures for now. The IE9 spec, the article says, allows for broader use, but I'm not sure what exactly that entails. In the meantime, you'll just have to use the .pdf file and not just it's base 64 string data.
this way worked for me :
var oldsrc = $('.content-control-iframe').attr('src');
var newsrc = $('.content-control-iframe').attr('src').slice(8);
$('.content-control-iframe[src="'+oldsrc+'"]').attr('src', newsrc);
As far as I know, IE doesn't handle the data: URL scheme at all, so I guess, it doesn't know what to pass to the PDF viewer. See WP.
Cheers,