Could someone please advise what the "correct" method is for adding HTML content to an ASP.NET page dynamically?
I am aware of the following declarative method.
//Declaration
<%= MyMethodCall() %>
//And in the code behind.
protected String MyMethodCall()
{
return "Test Value";
}
Is there a better or best practice way?
EDIT: I am building a Galleriffic photo gallery dynamically depending on the images located in a specific folder.
Depends what you want to do.
For controls/text I normally use a LiteralControl and set the Text property as the HTML I want to add, then this control can be added anywhere on the page that you want it to appear
LiteralControl reference is
here
ok seeing as you want it for Galleriffic, I guess it would pseudo-appear as such...
LiteralControl imageGallery = new LiteralControl();
string divStart = #"<div id='thumbs'><ul class='thumbs noscript'>";
imageGallery.Text += divStart;
foreach ([image in images])
{
string imageHTML = #"<li><a class='thumb' name='optionalCustomIdentifier' ref='path/to/slide' title='your image title'>
<img src='path/to/thumbnail' alt='your image title again for graceful degradation' /></a>
<div class='caption'>[caption]<div></li>";
imageGallery.Text += imageHTML;
}
string divEnd = #"</ul></div>";
imageGallery.Text += divEnd;
this.[divOnPage].Controls.Add(imageGallery);
Aspx :
<div id="DIV1" runat="server"></div>
Code behind :
DIV1.InnerHtml = "some text";
There are several ways to do that, which to use really depends on your scenario and preference.
Web User Controls: Can be added dynamically and you get the full editor support of Visual Studio.
XML literals (VB.NET only): Very convenient way to quickly put together HTML in code.
Templates: Add a plain HTML document to your solution and include it as a resource. Then you'll get editor support and you won't clutter your code with HTML source.
Another option
//.aspx
<asp:Literal ID="myText" runat="server"></asp:Literal>
//.aspx.cs
protected Literal myText;
myText.Text = "Hello, World!";
Related
I need to append a div (with is content), after all tags with a specific css class (or data- tag) in code behind of asp.net c#.
Someone can help me? Basically it should work as "append" in jquery. I searched online but could not find anything, especially to "append" to a tag with a specific CSS class.
Thank you.
You can add a diva as an html generic control from the code behind
for example i have a div like this
<div id="test" runat="server">Some Content</div>
As i specified runat server it will be available there and i can add contents like this
HtmlGenericControl div= HtmlGenericControl();
div.TagName = "div"; //specify the tag here
//then specify the attributes
div.Attributes["height"] = "100%";
div.Attributes["width"] = "100%";
div.Attributes["class"] = "someclass";
div.Attributes["id"] = "someid";
test.Controls.Add(div);
I have a Web Form project I am developing C# ASP.Net 4.5. I have a class that calls a response.write to display a message for user input validation purposes. The call to response.write is made inside the class in a method from creating a new instance of the class, thus the class method, by pressing a button on the form. But using the response.write causes the textboxes on my page to shrink considerably. Then when I press a different button the textboxes go back to normal. It only happens when I use response.write. Any help would be appreciated. Code call in class method:
HttpContext.Current.Response.Write("File not found");
By using that you're simply dumping text to the top of the page, typically outside of the <html> tags. This can have a knock-on effect to the rest of the pages style; i see the same when i am spitting out test responses.
Instead, put yourself a label control on your page and populate that instead. you can put it exactly where you want and simply call:
So put this: <asp:Label runat="Server" id="myLabel" /> where you want the message to appear.
Then in your code-behind, write this. It will populate the label with the given text.
myLabel.Text = "File not found";
The Label control will be rendered as a <span></span> - so styling it is nice and easy.
If you fancied using a <div> then use the Panel control.
If you're not fussed about any sort of style, go for a Literal control, which renders no html elements.
When you use the HttpContext.Current.Response.Write on code behind is direct send to the page your text, at any random point of page render.
Maybe on top, maybe on bottom, on some point that you can not control if you use the code behind to call it.
Change the way you show your message, at a minimum you can use a literal control to render there your output and show it.
You may want to use a control to display your error. For example:
In the aspx/ascx
<asp:Label id="ErrorMessage" runat="server" />
in the page/control code behind
//call TheClass
TheClass c = new TheClass();
string error = c.TheMethod();
if (!string.IsNullOrEmpty(error))
{
ErrorMessage.Text = error;
}
in TheClass
public class TheClass
{
public string TheMethod()
{
string result = "";
...
//When file is not found
result = "File not found";
...
return result;
}
}
I have some HTML code in a String variable in C#.
That code generated and stored in String variable at run-time.
But now I want to execute this code at run time.
All I want to do is see how that code looks in BROWSER.
How can I do this?
Is there any control in asp.net that provides such functionality?
you can use any contol like panel literal.
Suppose you have a string
string str="<p><div>Some Text</div></p>";
Literal1.Text = str;
html
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
in your .aspx put html tag (div, paragraph, label etc) with property runat=server
<p id="dynamicstring" runat="server"></p>
in codebehind
dynamicstring.InnerText= yourstring;
You can use StringBuilder and then Simply use Response.Write for StringBuilder
i have been trying to create controls dynamically on my web page using the StringBuilder class..and i dont quite seem to get through...
any help would be appreciated.
i am trying to do this...
StringBuilder sbTest = new StringBuilder(string.Empty);
sbTest.Append("<input type=\"text\" id=\"txt1\" runat=\"server\" />");
Response.Write(sbTest.ToString());
The page for sure displays a TextBox on the browser which is easily accessible through JavaScript...but what i want is the control to be available on the Server Side too...so that when the page is posted back to the server i can easliy obtain the value that has been entered by the user into the textbox.
Can any 1 please help me with this....
thank you so much....
Like Torbjörn Hansson says, if you just add a name attribute (and maybe remove runat="server" from your original snippet) you'll be able to access the submitted value but you'll only have a client-side HTML <input /> element.
If you are wanting to dynamically create server-side controls then you'll have to do something like this:
TextBox textbox = new TextBox {
/* take care to create unique ID's if you're adding more than 1 TextBox */
ID = "foo",
Text = "bar"
};
Controls.Add(textbox);
In an answer almost about the something I answered this
You should do the things properly and not trying to reinvent the wheel.
Creating controls Dynamically you can choose 2 ways, the .NET way, or the Javascript way
Both are seen by any of the other, in other words, creating controls using the .NET way, javascript can see and use it and vice versa.
.NET way
in your HTML file add something like
<body>
<form id="form" runat="server">
<asp:PlaceHolder id="ph" runat="server" />
</form>
</body>
in your script part
TextBox txt = new TextBox();
txt.ID = "myTxt";
ph.Controls.Add(txt);
you can easily get that TextBox in javascript using:
var myTxtValue = $("#myText").value();
Javascript Way
var txt = $("<input />", {
id : "myTxt"
});
txt.AppendTo("body");
in .NET you get the value using
string value = Request["myTxt"];
NOTE All javascript lines uses jQuery for simplify results
Provide a name-attribute and access it with:
Request.Form["txt1"]
You can get the value from
Request["txt1"]
Mind you, I am using master pages, but can I locate a div within the page and throw some html in there? Thanks.
You can add a div with runat="server" to the page:
<div runat="server" id="myDiv">
</div>
and then set its InnerHtml property from the code-behind:
myDiv.InnerHtml = "your html here";
If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:
<script type="text/javascript">
Sys.Application.add_load(MyLoad);
function MyLoad(sender) {
$get('<%= div.ClientID %>').innerHTML += " - text added on client";
}
</script>
Use asp:Panel for that. It translates into a div.
Remember using
myDiv.InnerHtml = "something";
will replace all HTML elements in myDIV. you need to append text to avoid that.In that this may help
myDiv.InnerHtml = "something" + myDiv.InnerText;
any html control in myDiv but not ASP html controls(as they are not rendered yet).
You could reference controls inside the master page this way:
void Page_Load()
{
ContentPlaceHolder cph;
Literal lit;
cph = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
if (cph != null) {
lit = (Literal) cph.FindControl("Literal1");
if (lit != null) {
lit.Text = "Some <b>HTML</b>";
}
}
}
In this example you have to put a Literal control in your ContentPlaceholder.
You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?
I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.
Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.