adding html elements with in asp.net - c#

I need some help figuring out how to do something.
I got this gallery (galleriffic) and some images that are store in Flicker.com so I used the flicker api to get the images but still add them manually to test the gallery.
Now I'm looking for a good way to insert the images into the html after I get them with the flicker api.
I found this htmltextwriter and used the function
Response.Write(GetDivElements());
but this is adding the div's on the top of the html and not inside the body tag.
my qustions is:
is HtmlTextWriter writer = new HtmlTextWriter(stringWriter) a good way to build html tags on the server side?
Is there a better way to add elements to the html other then Response.Write(""); ?

Here is what I do when I need to add mark-up.
in my page
<asp:PlaceHolder ID="MyPlaceholder" runat="server"></asp:PlaceHolder>
in my code behind
MyPlaceholder.Controls.Add(new Literal() { Text="<div>some markup</div>"});
I do it this way because:
1) you can put the PlaceHolder where you need it in the structure of your page
2) by adding a Literal at runtime to the Controls collection prevents ViewState getting bloated with it's contents.

If you are using the older style of asp.net, and not asp.net MVC, then you can just create a div with an id and runat="server". Then you can just write directly to the html.
aspx page
<div id = "DivINeedToAddStuffTo" runat="server" />
aspx.cs
DivINeedToAddStuffTo.InnerHtml = GetDivElements();
Also, I do not see anything wrong with using HtmlTextWriter to create your Html markup

You might try looking into Placeholders. That way you can create an instance of an image control and then add it your your placeholder.
Image myImg = new Image();
myImg.ImageUrl = "MyPicture.jpg";
myPlaceholder.Controls.Add(myImg);

You should be able to use the ASP literal control:
foreach (var item in items)
{
Literal literal = new Literal();
literal.text = item.html; //Assuming the item contains the html.
MyPlaceholder.Controls.Add(literal);
}
You could have that code before the page has rendered.
Hope that helps
Paul
EDIT
Sorry, I think I was mistaken, I thought you had the html with the link to the image(s) and not the actual image itself, Justin's answer would suit you if that's the case.

var ctrl = new WebControl(HtmlTextWriterTag.Div) { CssClass = "SomeClass" };
ctrl.Attributes["style"] = "float:left;display:inline-block;margin:3px;";
ctrl.Controls.Add(new Image
{
ImageUrl =
Page.ResolveUrl("image path here")
});
this.Controls.Add(ctrl);

Related

Read the tag content of Open Graph from code behind

I need to read the tag content of og:image in the page header from code behind. How can I do that?
<meta property="og:image" name="og:image" content="mydomain.com/testing.jpeg" />
The string that I want to read from code behind is "mydomain.com/testing.jpeg".
The head tag for aspx pages has the 'run at server' attribute set so you can programmatically access it from code.
To solve your specific question:
var stuffWrapper = this.head.Parent.Controls[0];//("og:image");
var stuff = ((System.Web.UI.HtmlControls.HtmlMeta)stuffWrapper).Content;
Normally you would use the .FindControl method on your controls collection to get programmatic access to the aspx tag. Not sure what 'dotted-notation-path' you would have to discover to allow the .FindControl method to work.
So, in this specific case you will have to know what zero-indexed location your meta tag is within the head tag. And if you reorder the tags in the header in the future your code will behave badly.
You can also generate the meta tags from code behind. That way you have full control.
HtmlMeta meta = new HtmlMeta();
meta.Name = "og:image";
meta.Content = "mydomain.com/testing.jpeg";
Page.Header.Controls.Add(meta);

how to click a specific div and get information from it asp.net c#

I am making a table for schedule and putting div's on the table. People can make new appointments by clicking on one of the div .
I am changing the activeview when a div is clicked. I need to embed information in the div's so I can use it in the database and I want to know which div is clicked.
How can I solve this? Here is my code:
HtmlGenericControl div = new HtmlGenericControl("DIV");
div.Style.Add(HtmlTextWriterStyle.Width, "60px");
div.Style.Add(HtmlTextWriterStyle.MarginTop, "1px");
div.Style.Add(HtmlTextWriterStyle.BackgroundColor, "green");
div.Style.Add(HtmlTextWriterStyle.Height, last * 40 + "px");
div.Attributes.Add("onclick", "somefunction()");
div.Style.Add("cursor", "pointer");
bul.Controls.Add(div);
bul is a table cell where I put a DIV.
Don't forget to set an ID in your div server control
see this url which explains you how reference your server control in javascript:
http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/
Excerpt from article:
$get('<%= yourdiv.ClientID %>')
<script>
alert('yourdiv has a value of: ' + $get('<%= yourdiv.ClientID %>').value);
</script>
IMHO, you need to rethink about your approach.
I think you will need to seperate the solution into 3 different parts:
1- Server-side code: which will get the information about current appointments, and to save the new appointment that your audience may create.
2- Markup code: which should contain the basic building blocks for your markup, and not to generate everything from your server-side code, as #Senfo has suggested.
3- You should use some client-side code (Javascript) in order to switch between the normal-view mode, and the create-view mode.
4- if you don't want to use client-side code, you should decorate your div with 2 attributes in order to be able to deal with them in your C# code:
ID (which should be unique per every div)
Runat="Server" attribute
I know that my solution is not complete, but considering that this is a homework question, I think it's better to guide you to the correct path, but to let you move on according to these principles.
I think you can make it, and you should now create a much cleaner solution.
if you still can't figure it out, I will try to give you an example, but my advice is to take a deep breath, and start by your own :)
> .answer {
width:20px;
height:20px;
border-color:Red;
border:1px;
background-color:Green;
HtmlGenericControl div = new HtmlGenericControl("DIV");
div.ID = "testDiv";
div.Attributes.Add("class", "answer");
div.Attributes.Add("onclick", "somefunction(this)");
this.Controls.Add(div); // this code shlould be on pageload
<script language="javascript">
function somefunction(obj)
{
alert(obj.id);
}

Modify Stylesheet properties in ASP.NET MVC

I am preloading stylesheets inside this method OnResultExecuting(ResultExecutingContext filterContext) in MVC, this is just to make sure that this is done before the actionResult is called when loading the page, and this works fine, my issue is now i want to modify the style sheet background-image property in a class called logo and before the tag is built(code below) and added to the head section in the DOM, I'm wondering if there isn't a way to read(StreamReader?/StreamWriter?) the css file and modify it and save it before the tag is built or something like that, btw Im getting the css file from the server.
foreach (string file in filepath)
{
if (Path.GetExtension(file).ToLower() == ".css")
{
TagBuilder link = new TagBuilder("link");
link.Attributes["rel"] = "stylesheet";
link.Attributes["type"] = "text/css";
link.Attributes["href"] = urlHelper.Content(
string.Format("~/Content/themes/Theme{0}/{1}",
setting.ThemeId, Path.GetFileName(file)));
resources.Add(MvcHtmlString.Create(link.ToString(TagRenderMode.SelfClosing)));
}
}
You could just load another style sheet after this one and amend class style that way, infact that's exactly how I do this for my white label solution.
CanĀ“t you use LESS to dinamicaly create your css?
http://www.dotlesscss.org/
http://karlmendes.com/2010/07/using-less-css-for-net-with-asp-net-mvc-2/
Maybe it will make things easier for you...

printing html in asp.net

What's the best way for print html?
I can do this:
container.InnerHtml = "<input type=\"text\" ...runat=..>";
where container is an ref to an <div> HTML
but I have impression that this it's not the correct mode.
can someone point me for right direction?
Thanks in advance.
As Paolo has mentioned, using the <asp:PlaceHolder> is a good way to inject HTML at runtime. Not only does it allow for you to output plain html <div><p>Hello World!</p></div> but it also allows you to dynamically add other asp.net controls.
For your example above you could do
.aspx
<asp:PlaceHolder id="PlaceHolder1" runat="server" />
c#
TextBox textBox1 = new TextBox();
textBox1.Id = "textBox1";
textBox1.TextMode = TextBoxMode.SingleLine;
PlaceHolder1.Controls.Add(textBox1);
This then allows you to access the value which you enter into textBox1 dynamically.
if by "printing HTML" you mean injecting it at runtime in a ASP.NET webform, you may try using a PlaceHolder

Check Empty XML data validation before displaying

I want to check xml before displaying it .I am using XPath not xsl for it. For e.g.
<title></title>
<url></url>
<submit></submit>
i wanna check that if xml data is not there for it . Then don't display it. because I m putting these values in <a href=<%#container.dataitem,url%>>new link</a>.
So i want that if url is empty then don't display new link otherwise display it and similarly for title that if title is not empty display it otherwise don't display it.
Main problem is I can check like in ascx.cs file
if(iterator.current.value="") don't display it but the problem is in ascx file i m givin
new link
i want that new link should not come if url is empty...
Any idea how to check this condition?
I've seen this handled using an asp:Literal control.
In the web form, you'd have <asp:Literal id='literal' runat='server' text='<%# GetAnchorTag(container.dataitem) %>' />
And in the code behind, you'd have:
protected string GetAnchorTag(object dataItem) {
if(dataItem != null) {
string url = Convert.ToString(DataBinder.Eval(dataItem, "url"));
if(!string.IsNullOrEmpty(url)) {
string anchor = /* build your anchor tag */
return anchor;
}
}
return string.Empty;
}
this way, you either output a full anchor tag or an empty string. I don't know how this would fit in with your title and submit nodes, but it solves the anchor display issue.
Personally, I don't like this approach, but I've seen it quite a bit.
Use XPath. Assuming that the elements are enclosed in an element named link:
link[title != '' and url !='']
will find you the link elements whose title and url child elements contain no descendant text nodes. To make it a little more bulletproof,
link[normalize-space(title) != '' and normalize-space(url) !='']
will keep the expression from matching link elements whose title or url children contain whitespace.
If you don't have access to the .cs file for this then you can still embed the code right in the .ascx file. Remember, you don't HAVE to put all your code in the code behind file, it can go inline right inside the .ascx file.
<%
if(iterator.current.value!="") {
%>
<a href=<%#container.dataitem,url%>>new link</a>
<%
}
%>
what about //a[not(./#href) or not(text()='']

Categories