Create dynamic .aspx pages in asp.net - c#

The following code creates file.aspx and file.aspx.cs:
protected void Button1_Click(object sender, EventArgs e)
{
string fielName = Server.MapPath("~/file.aspx");
TextWriter tw = new StreamWriter(fielName);
tw.WriteLine(#"<%# Page Language=""C#"" AutoEventWireup=""true"" CodeFile=""file.aspx.cs"" Inherits=""file"" %>
<!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"">
<div>
</div>
</form>
</body>
</html>
");
tw.Close();
tw = new StreamWriter(fielName + ".cs");
tw.WriteLine(#"using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class file : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(""new File "");
}
}
");
tw.Close();
}
I want to make the page name written in my Textbox.
I have tried putting textbox in html source of above code, but I'm getting an error.
CodeFile="""+TextBox1.Text+""" Inherits="""+TextBox1.Text+"""

You would be much farther ahead to work the way ASP.NET "thinks" about the page. I once worked on a very large, dynamic questionnaire. All of the controls were generated dynamically along with validations and everything else. At it's core, the way we did it was:
place a panel on the page
add controls to the panel
the code very roughly would look something like this:
var btn = new Button();
btn.ID = "theId";
btn.Text = "hi";
pnlDynamic.Controls.Add(btn);
Because you're dealing with dynamic controls, you might also want to make sure that you understand the page life-cycle...: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

Make sure your web project is declared as a web site rather than a web application.
A web site is willing to dynamically compile each page on demand, unlike a web application, so something like this is in principle doable. If you really want to do it.

Related

Calling Dynamically Created Textboxes in C# Visual Studio

In this post I wanted to figure out how to create dynamically created textboxes in C# Visual Studio.
Adding additional textboxes to aspx based on xml
However, when I try to call the ID of these dynamically created textboxes later in my code to figure out what text the user entered into them, I am getting an error that says these IDs do not exist in the current context. Does anyone know how I would be able to call these?
credit to Adding additional textboxes to aspx based on xml
Here is my entire code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
namespace WebApplication4
{
public partial class WebForm15 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsCallback)
{
//credit to https://stackoverflow.com/questions/44076955/adding-additional-textboxes-to-aspx-based-on-xml#comment75336978_44078684
const string xml = #"<Number>
<Num>1</Num>
<Num>2</Num>
<Num>3</Num>
</Number>";
XDocument doc = XDocument.Parse(xml);
int i = 0;
foreach (XElement num in doc.Root.Elements())
{
TextBox box = new TextBox
{
ID = "dynamicTextBox" + i,
Text = num.Value,
ReadOnly = false
};
divToAddTo.Controls.Add(box);
divToAddTo.Controls.Add(new LiteralControl("<br/>"));
i++;
}
}
}
protected void BtnGetValues_Click(object sender, EventArgs e)
{
IList<string> valueReturnArray = new List<string>();
foreach (Control d in divToAddTo.Controls)
{
if (d is TextBox)
{
valueReturnArray.Add(((TextBox)d).Text);
}
}
//valueReturnArray will now contain the values of all the textboxes
}
}
}
Here is aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm15.aspx.cs" Inherits="WebApplication4.WebForm15" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="divToAddTo" runat="server" />
<asp:Button runat="server" ID="BtnGetValues" Text="GetValues" OnClick="BtnGetValues_Click" />
</form>
</body>
</html>
Figured it out!!! Here is what I found after scouring the internet for hours
Solution:
When using dynamic controls, you must remember that they will exist only until the next postback.ASP.NET will not re-create a dynamically added control. If you need to re-create a control multiple times, you should perform the control creation in the PageLoad event handler ( As currently you are just creating only for first time the TextBox using Condition: !IsPostabck ). This has the additional benefit of allowing you to use view state with your dynamic control. Even though view state is normally restored before the Page.Load event, if you create a control in the handler for the PageLoad event, ASP.NET will apply any view state information that it has after the PageLoad event handler ends.
So, Remove the Condition: !IsPostback, So that each time the page Loads, The TextBox control is also created. You will also see the State of Text box saved after PageLoad handler completes. [ Obviously you have not disabled ViewState!!! ]
Example:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtBox = new TextBox();
// Assign some text and an ID so you can retrieve it later.
txtBox.ID = "newButton";
PlaceHolder1.Controls.Add(txtBox);
}
Now after running it, type anything in text box and see what happens when you click any button that causes postback. The Text Box still has maintained its State!!!

Print webbrowser content as landscape

I need to print document from WebBrowser control as landscape (without showing PrintPreview and changing default printer page orientation).
I've tried:
TemplatePrinter
Here's my template template.html:
<HTML XMLNS:IE>
<HEAD>
<?IMPORT NAMESPACE="IE" IMPLEMENTATION="#default">
<TITLE>Landscape</TITLE>
</HEAD>
<BODY>
<IE:TEMPLATEPRINTER id="Printer"/>
<SCRIPT Language="JavaScript">
Printer.orientation="landscape";
</SCRIPT>
</BODY>
</HTML>
And I try to use it:
mshtml.IHTMLDocument2 doc = wbReport.Document.DomDocument as mshtml.IHTMLDocument2;
doc.execCommand("print", false, "template.tpl");
Create reg key "orientation" with value "2" in HKCU\Software\Microsoft\Internet Explorer\PageSetup
Add style like:
<style type="text/css" media="print">
#page
{
size: landscape;
margin: 2cm;
}
</style>
But I still print my html as portrait.
Maybe there is better solution to print html as landscape or I have some mistakes when using TemplatePrinter?
After messing around with the registry, attempting to use print templates in IE and various other methods (none of which worked) i've produced a somewhat hacky workaround.
I've extended the WebBrowser control and created a new print preview method inside which I have methods to pass the ALT+L key combination to enable landscape view:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace YourProjectNamespace
{
class ExWebBrowser : WebBrowser
{
void setLandscapeTimer_Tick(object sender, EventArgs e)
{
SendKeys.SendWait("%L");
this.ProcessDialogKey(Keys.Alt & Keys.L);
SendKeys.Flush();
}
public void _ShowPrintPreviewDialog()
{
this.ShowPrintPreviewDialog();
this.Focus();
Timer setLandscapeTimer = new Timer();
setLandscapeTimer.Interval = 500;
setLandscapeTimer.Tick += new EventHandler(setLandscapeTimer_Tick);
setLandscapeTimer.Start();
}
}
}
All you need to do is simply instantiate the object, load a document as with the standard WebBrowser and call _ShowPrintPreviewDialog.
Note you may want to stop the timer once the landscape view has been set.
HTH somebody with the same issue.

How to display partial HTML page in Windows 8 metro app

Let's say I have the following page:
<html>
<body>
<content1>
</content1>
<content2>
</content2>
<content3>
</content3>
</body>
</html>
I want in my Metro app to display only the part of the page contained between <content2></content2>. For a full page I would use a <WebView> and the Navigate() method. But I don't seem to find a way to adapt that to what I need.
to actually write any solution code I would need to know what are Content1 and content3. assuming them being DIV with an ID, I can say
void WebView5_LoadCompleted(object sender, NavigationEventArgs e)
{
string script = #"var d=document.getElementById('content1');d.style.visibility='hidden'";
string[] args = { script };
string foo = WebView5.InvokeScript("eval", args);
}`

Change html code on server side asp.net

I want to change some string located in html file when it loads. For example, i have a html file:
<html>
<head>
<title>MyTitle</title></head>
<body>
Some Text
<script type='text/javascript'>
/*some script*/
var myString = "TargerInfo";
/*some script*/
</script>
</body>
</html>
I use Page_Load method in code-behind file:
protected void Page_Load(object sender, EventArgs e)
{
/*Insert necessary snippet of code*/
}
What code should i use to change string "TargerInfo" to "OtherString" ?
[EDIT]
Sorry, that I have forgot to mention
I can add any info to html page only in code-behind class, because this page isn't generated by me.
I think i should use something like this:
1) load html file
2) find my string
3) replace it
4) send html file
There is an aspx page, but i add only some part of code and other code is added by VS
Unless I'm missing something (because this seems like a bit of an ASP.NET 101), you have several options...
Create a variable in the code-behind and then use that...
protected string _newText = "";
protected void Page_Load(object sender, EventArgs e)
{
_newText = "OtherString";
}
And then in the ASPX...
var myString = "<%=_newText%>";
Otherwise you can use the <asp:Literal> control
UPDATE
After an extensive chat with #andDaviD it turns out that the javascript is in a Master page held in SharePoint Foundation.
The Master page is being referenced in his Content page via the DynamicMasterPageFile attribute in the <%# Page directive, and that is why he said he is able to update some part of the code, but not others.
I am still unsure as to whether it is possible for the Master page to be modified (either by himself or an administrator), that is something he needs to find out from the people in charge at his company. But I believe the adding of a property or method to the Master Page to provide what he needs is the only sensible option.
You could use inline aspx code tags:
<script type='text/javascript'>
/*some script*/
var myString = "<%= getTargetInfo() %>";
/*some script*/
</script>
in codebehind:
protected String getTargetInfo()
{
return "OtherString";
}
You could use a literal:
protected void Page_Load(object sender, EventArgs e)
{
literal.Text = string.Format("var myString = \"{0}\"", targetInfoValue);
}
Markup:
<html>
<head>
<title>MyTitle</title></head>
<body>
Some Text
<script type='text/javascript'>
/*some script*/
<asp:Literal id="literal" runat="server" />
/*some script*/
</script>
</body>
</html>
You can have it in a hiddenfield in asp.net and change the hidden field in code behind.
in your code behind:
public string otherString;
otherString = "some text" //update the string with the value oyu want.
in aspx page put this line in any place you want to see the otherString.
<%=otherString%>

ASP.NET C# scope issue

OK, so I'm tyring to work with some simple stuff in ASP.NET and C# to get the hang of the super super basics, and I'm having trouble finding out how I can get this scope issue to work. At least, I think it's a scope issue! :)
So, here is my Default.aspx presentation markup:
<%# Page Language="C#" Inherits="project1.Tree" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>project1_test</title>
</head>
<body>
<form runat="server">
<p><asp:label runat="server" id="lblOutput" /></p>
<asp:TextBox ID="txtGrowBy" runat="server" />
<asp:Button id="btnGrow" runat="server" Text="Grow!!!" />
</form>
</body>
</html>
And here is my CodeBehind file:
using System;
using System.Web;
using System.Web.UI;
namespace project1
{
public partial class Tree : System.Web.UI.Page
{
public int height = 0;
public void Grow(int heightToGrow) {
height += heightToGrow;
}
protected void Page_Load(Object Source, EventArgs E)
{
Tree tree1 = new Tree();
string msg = "Let's plant a tree!<br/>";
msg += "I've created a tree with a height of " +
tree1.height + " metres.<br/>";
lblOutput.Text = msg;
}
public virtual void btnGrowClicked (object sender, EventArgs args)
{
txtGrowBy.Text = tree1.heightToGrow;
}
}
}
Now, I believe the issue lies with the fact that I'm not using a getter and sender, but I'm not 100% sure.
I take it you're variable height is not being maintained between postbacks?
This is because the web is stateless. Your variables are not maintained between postbacks unless you store the values in Session, ViewState or Hidden Fields. So you could do the following to maintain your height value between PostBacks:
ASPX:
<form runat="server">
<asp:HiddenField id="hd_Height" runat="server" />
</form>
Code Behind:
public int Height
{
get
{
return int.Parse(hd_Height.Value).ToString();
}
set
{
hd_Height.Value = value.ToString();
}
}
There's several immediate problems with your code; in the Page_Load method, you're creating a new Tree instance - you don't have to do this, as one was automatically created by IIS when the ASP.NET page was accessed. Use the this keyword in the Page_Load method to get access to that instance.
Further, nothing ever seems to call the Grow method; is this intentional? Shouldn't you be calling that from within the btnGrowClicked method?
And finally as GenericTypeTea points out, your height field won't be maintained between Postbacks. Easiest way to do this is with session state, eg:
private void PersistHeight(int height)
{
this.Session["height"] = height;
}
private int RestoreHeight()
{
return (int)this.Session["height"];
}
You could use viewstate as well (if Mono supports it); simply add the updated value to viewstate before giving control back to the browser. Then read from viewstate the original value saved in the last postback and incrementing the new value to it:
public int MyValue
{
get {return Convert.ToInt32(viewstate["myVal"]);}
set {viewstate["myVal"] = value;}
}
I hope that makes sense.

Categories