autoresize iframe not working - c#

my html code is
<script language="JavaScript" type="text/javascript">
function autoResize(id)
{
var newheight;
var newwidth;
if (document.getElementById)
{
newheight = document.getElementById(id).contentWindow.document.body.scrollHeight;
newwidth = document.getElementById(id).contentWindow.document.body.scrollWidth;
}
document.getElementById(id).height = (newheight) + "px";
document.getElementById(id).width = (newwidth) + "px";
}
</script>
<asp:DataList ID="dtlhtml" runat="server" Width="100%">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
<iframe src='<%#Eval("html") %>' width="713" height="250" id="iframe1" frameborder="0" onload="autoResize(this.id);"></iframe>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
.cs code on page load event
DataTable dt1 = new DataTable();
dt1.Columns.Add("html");
DataRow dr = dt1.NewRow();
dr["html"] = "";//Any dynamic url path
dt1.Rows.Add(dr);
dtlhtml.DataSource = dt1;
dtlhtml.DataBind();
this is not working in local but working fine on online
Problem
I am running it online on firefox with version 24.0 is running fine but on my 2 friend pc with same version scrolling is coming.

your if condition is incorrect, do as below
if(document.getElementById(id))
{
}

I am not sure though, but I guess problem lies here: Numeric value + string might be causing error.
document.getElementById(id).height = (newheight) + "px";
document.getElementById(id).width = (newwidth) + "px";
You can instead write this as
document.getElementById(id).height = newheight;
document.getElementById(id).width = newwidth;
ALso you can remove 'px' because by default lengths are in pixel only.

Hey my problem is solved as i was giving path as
dr["html"] = "http://stackoverflow.com/file/1.html";
but the proper way was to give path for calling html page to my iframe was to be
dr["html"] ="http://www.stackoverflow.com/file/1.html"

Related

Set innerHTML value to a div element from code behind using a string as the div ID

I am using the below code in my .aspx page.
<form runat="server">
<div style="background:#ffffff;height:1150px;width:100%">
<center>
<table class="calendar-table" cellpadding="0" cellspacing="2" border="1">
<tr>
<td>
<div class="cell">
<div class="cell-day">
<asp:Label ID="label_day_11" runat="server" Text=""></asp:Label>
</div>
<div id="event_11" runat="server">
</div>
</div>
</td>
</tr>
<table>
</center>
</div>
</form>
In my original code I will have a total of 6 rows and 7 columns and the label rows and columns will go from 11 till 67 in the form of a matrix. Here I would like to set the value of label_day_11 from code behind using C# and for that I am using the below code,
int i = 1; // 1 till 6 rows
int j = 1; // 1 till 7 columns
string dayId = "label_day_" + i.ToString() + j.ToString();
Label day = FindControl(dayId) as Label;
day.Text = "Monday";
The above code works fine. But now I want to assign a innerHTML value to the event_11 div element also. But I am not sure how to get that ID and how to set the innerHTML. Is there any way to access the div control using a string in C# and then set a innerHTML value to it? In case of a asp:Label I used the control value as Label but not sure how to get the control of a normal html div element.
I tried the below code but it does not work for me.
string eventId = "event_" + i.ToString() + j.ToString();
Control div = FindControl(eventId);
StringWriter sw = new StringWriter();
HtmlTextWriter w = new HtmlTextWriter(sw);
div.RenderControl(w);
I am not sure how to proceed using this. Any solutions?
I think it should work if you cast it to HtmlGenericControl.
HtmlGenericControl div = FindControl(eventId) as HtmlGenericControl;
div.InnerHtml = "your inner html";
https://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlgenericcontrol(v=vs.110).aspx

asp.net how render html input radio to postback

I'm using the code below to create radio buttons dynamically to a webpage as each set of data is retrieved from a database by iteration. It works well. The only problem is I need these to PostBack so further data can be retrieved depending on which radio button is clicked. I tried doing this with RadioButton controls but these wouldn't position inside of a table cell like the <span> technique does and they wouldn't create through a <span>.
int count = 0;
if (dataReader.HasRows)
{
testLabel1.Text = "dataReader.HasRows: " + dataReader.HasRows;
while (dataReader.Read())
{
count += 1;
htmlString.Append("<table border = '1'>");
htmlString.Append("<tr>");
htmlString.Append("<td>");
htmlString.Append(dataReader["dateTime"] + "<br />" + "<span><input type='radio' id='rd1'/>SOMTEXT </span>" + dataReader["statistics"]");
htmlString.Append("</td>");
htmlString.Append("</tr>");
htmlString.Append("</table>");
htmlString.Append("<br />");
}
test_populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
dataReader.Close();
dataReader.Dispose();
}
}
}
}
I tried adding runat="server" in <span><input type='radio' id='rd1'runat='server'/>SOMTEXT </span> but it didn't create the radio button. Thanks in advance.
Don't know, how to format code in comment. One more again - if you write runat="Server" in your hand-made html, it does nothing, because this code will not be compiled, you just write html answer manually. On the other hand compilation of declarative language (asp.net, razor or any other) makes javascript, you can do it manually too, but B.Gates kindly agreed to do it for you :-)
Asp.Net design
<%# 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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" >
<HeaderTemplate>
<table border ="1">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td style="width:200px">
<asp:Label runat="server" ID="Label1"
/>
</td>
<td style="width:200px" >
<asp:RadioButton ID="RadioButton1" runat="server" Checked="false" Text = '<%# Eval("Text") %>' AutoPostBack ="true" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
C# CodeBehind
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int num = 10;
if (Page.IsPostBack)
{
for (int i = 1; i < this.Repeater1.Controls.Count-1; i++)
{
RadioButton r = (RadioButton)this.Repeater1.Controls[i].Controls[3];
if (r.Checked)
{
num=int.Parse(r.Text.Substring(0, r.Text.IndexOf(' ')));
break;
}
}
}
this.Repeater1.DataSource = GetAll(num);
this.Repeater1.DataBind();
}
DataTable GetAll(int count)
{
Random r = new Random();
DataTable dt = new DataTable();
dt.Columns.Add("Text", typeof(string));
DateTime bs = DateTime.Now;
for (int i = 0; i < count; i++)
{
int value = r.Next(3, 10);
dt.Rows.Add(value.ToString() + " rows will be shown");
}
return dt;
}
}
Method GetAll() returns table, having count lines. In each line is text "%i rows will be shown" with random number. Table is bind to data repeater on page load event. If it is postback, number of rows is parsed from text of radiobutton inside repeater row (you can't get it from data table, it is another page, data table is already in GC)

How to allow user to download or view file saved in the server

my web form creates a file and saves it to a folder in the server that the user can click on and view it in browser:
<asp:Repeater runat="server" ID="rptContent" OnItemCommand="btnGeneratePDF_Click">
<HeaderTemplate>
<table id="tblResponse">
<tr id="hdrRow">
<td style="width: 25%;">Name</td>
<td style="width: 25%;">Last Four SSN #</td>
<td style="width: 25%;">PDF Generator</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="trNormal">
<td><%# Eval("name").ToString() %></td>
<td><%# Eval("ssn3").ToString() %></td>
<td><asp:Button ID="btnGeneratePDF" ClientIDMode="Static" runat="server" Text="Generate PDF" CommandArgument='<%# Eval("name").ToString() + ", " + Eval("ssn3").ToString() %>' /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
When the user clicks on the Generate PDF button it currently displays a link to the file the user can click on to view the file. The code behind is here:
public void writeData(string k, string c)
{
Conn = new SqlConnection(cString);
Conn.Open();
string pdfTemplate = Path.Combine(Server.MapPath("~/PDFTemplates/forme.pdf"));
//MessageBox.Show(pdfTemplate);
string newFile = strDirectory + "completed_pdf_" + k + ".pdf";
newFileServer = System.Environment.MachineName + #"/PDFGenerate/completed_pdf_" + k + ".pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
//if more than multiple entries, verify by name and the last four ssn
sqlCode = "SELECT * FROM [Db].[dbo].[TablePDF] WHERE [name] = '" + k + "' AND [ssn3] = " + c + "";
//MessageBox.Show("" + sqlCode.ToString());
using (SqlCommand command = new SqlCommand(sqlCode, Conn))
{
command.CommandType = CommandType.Text;
using (reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
pdfFormFields.SetField("lName", reader.GetValue(0).ToString());
pdfFormFields.SetField("fName", reader.GetValue(1).ToString());
pdfFormFields.SetField("cbMALEpg3", "Yes");
tc.Text = "A completed PDF for " + k + " was generated successfully and saved to <a target=_blank href=/PDFGenerate/completed_pdf_" + k + ".pdf>//" + newFileServer + "</a>";
strFullPath = Path.GetFullPath("//" + newFileServer);
List<System.Web.UI.WebControls.ListItem> files = new List<System.Web.UI.WebControls.ListItem>();
files.Add(new System.Web.UI.WebControls.ListItem(strFullPath, strFullPath));
GridView1.DataSource = files;
GridView1.DataBind();
}
}
}
}
pdfStamper.FormFlattening = false; //allow user to modify the form once it has been saved. Set to TRUE otherwise.
// close the pdf
pdfStamper.Close();
Conn.Close();
}
The above codes work fine, where the button generates a link in the tc label and I am able to click and view the file in the browser.
The tc label shows this which is a link I can click on and view the pdf file:
A completed PDF for bill was generated successfully and saved to //server/PDFGenerate/completed_pdf_bill.pdf
Side note: I created a virtual folder in my site in IIS pointing to the physical folder in the server which stores the files, making the above link work.
The GridView code portion above is to populate a table with the link and a DOWNLOAD and VIEW option that I added on my page here:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No PDF was generated">
<Columns>
<asp:BoundField DataField="Text" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text = "Download" runat="server" OnClick = "DownloadFile" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID = "lnkView" Text = "View" runat = "server" OnClick = "ViewFile" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I also added the following code to handle the DOWNLOAD command:
protected void DownloadFile(object sender, EventArgs e)
{
string strFilePath = Path.GetFullPath("\\\\" + newFileServer);
MessageBox.Show(strFilePath);
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFullPath);
MessageBox.Show(strFullPath);
Response.WriteFile(strFilePath);
Response.End();
}
I will be accessing that outside of the server that it is on from a local PC which is still in the same network. When I click on the DOWNLOAD link, I get an error: The UNC path should be of the form \\server\share
Right now, the GridView is populating correctly, but the DOWNLOAD link isn't working inside the GridView.
How can I fix the code so the DOWNLOAD link works? Also, what would be the code so make the VIEW link work the way it is currently working in the tc label?
Just stream the bytes back.
byte[] fileByteArray = File.ReadAllBytes(Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "MyPDF.pdf"));
Response.AddHeader("Content-disposition", String.Format("attachment; filename={0}.pdf", "MyTestFile"));
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(fileByteArray);
UPDATE
Since your files are on the same server hosting your page there is no reason you need to share off the directory if users are only accessing them via your site. Keeping the share either way doesn't matter but there is no need to call a UNC path when the files are local to the page.
I would remove the share and use the following
string myFilename = "report.pdf"
byte[] fileByteArray = File.ReadAllBytes(Path.Combine(#"C:\PDFFolder", myFilename));

Setting background image in a repeater

I am trying to set a background image in a repeater programmatically. Variations of the following have not worked, including trying to set the url in the div, not the jquery function:
The JQuery function:
var getBackgroundImage = function (imagePath) {
var backgroundImage = 'url(' + iipServ + '?FIF=/IIPServer/images/' + imagePath + '&WID=40&CVT=PNG' + ')';
return backgroundImage;
};
The ASP page:
<asp:Repeater ID="docResults" runat="server" ItemType="ArchiveViewer.Models.Document"
SelectMethod="GetSearchResults" >
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>"
data-objData="<%#:Item.JSONPath %>"
style="<%= getBackgroundImage(Item.Pages.First().ImagePath) %> ">
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
</asp:Repeater>
Can this be done? How?
Thank you!
EDIT: Each div has its own image. I'm getting the URL from the server.
EDIT 2: I am not instead of using a jquery function, am using a web method in my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = "background-image : url('" + iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)'";
System.Diagnostics.Debug.WriteLine(urlString);
return urlString;
}
In the ASPX page:
style="background-image : <%=getBackgroundImage(Item.Pages.First().ImagePath) %>">
In the code behind:
public string getBackgroundImage(string iipServ, string path)
{
return "url('" + iipServ + "?FIF=/IIPServer/images/" + path + "&WID=40&CVT=PNG)'";
}
It's not clear what iipServ is and where to take it from. Just pass it to the C# function along the path.
You should remove the JS function, this will be all server-side.
pid: Your answer is almost correct, but the compiler didn't like it. It helped me figure out how to do it correctly, though. Thank you.
In case it helps someone else, here is how I fixed this issue:
My ASPX page:
<ItemTemplate>
<div class="result" data-docid="<%#:Item.DocumentId %>"
data-imageDir="<%#:Item.FolderPath %>" data-objData="<%#:Item.JSONPath %>"
style="<%#: getBackgroundImage(Item.Pages.First().ImagePath) %>" >
<%#:Item.Metadata.Title %>
</div>
</ItemTemplate>
And my code behind:
[WebMethod]
public string getBackgroundImage(string path)
{
string iipServer = ConfigurationManager.ConnectionStrings["iipServer"].ConnectionString;
string urlString = #"background-image:url("
+ iipServer + "?FIF=/IIPServer/images/" +
path + "&WID=40&CVT=PNG)";
return urlString;
}

Iframe autoresizing height from codebehind in C#

My html page is
<iframe runat="server" id="iframe1" width="100%" height="100%" scrolling="no" frameborder="0"></iframe>
.cs content in my pageload event
iframe1.Attributes["src"] = "http://default.com/";
//iframe1.Attributes["height"] = "100%";
//iframe1.Attributes["width"] = "100%";
iframe1.Attributes.Add("style","width:100%;height:100%;");
But its not working
i want to display whole page content but my height of iframe is not taking the height of http://default.com/
I don't know how to autoresize iframe on .cs page but It's another option like put your iframe in datalist control like...
<asp:DataList ID="dtlhtml" runat="server" Width="100%">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
<iframe src='<%#Eval("html") %>' width="713" id="iframe1"
frameborder="0" onLoad="autoResize 'iframe1');">
</iframe>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Put javascript code as...
<script language="JavaScript">
function autoResize(id)
{
var newheight;
var newwidth;
if (document.getElementById(id))
{
newheight = document.getElementById(id).contentWindow.document.body.scrollHeight;
newwidth = document.getElementById(id).contentWindow.document.body.scrollWidth;
}
document.getElementById(id).height = (newheight) + "px";
document.getElementById(id).width = (newwidth) + "px";
}
</script>
And put on .cs page.
DataTable dt1 = new DataTable();
dt1.Columns.Add("html");
DataRow dr = dt1.NewRow();
dr["html"] = "";//Any dynamic url path
dt1.Rows.Add(dr);
dtlhtml.DataSource = dt1;
dtlhtml.DataBind();
NOTE:
This will not work in local host ..please try it on online.
I assume you don't want 'scrolling', so why not disable it?
<iframe src="/default.asp" width="100%" height="100%" scrolling="no"></iframe>
or try
iframe1.Attributes.Add("scrolling","no");
Edit: Try
PlaceHolder1.Controls.Add(new LiteralControl("<iframe src='mypage.aspx' width='100%' height='100%' scrolling='no'></iframe>"));
or
iframe1.Attributes["src"] = "http://www.asp.net";
Since you are using runat="server" so you can access the attributes like height and width from code behind.
Try
Updated Answer
iFrame1.Attributes.Add("height","100%");
iFrame1.Attributes.Add("width","100%");
set scrolling ="no" inside tag as suggested by Paul

Categories