Dynamically generated HTML in C# to be formatted - asp.net

I have an ASP.NET web forms site with a rather large menu. The HTML for the menu is dynamically generated via a method in the C# as a string. I.e., what is being returned is something like this:
<ul><li><a href='default.aspx?param=1&anotherparam=2'>LINK</a></li></ul>
Except it is a lot bigger, and the lists are nested up to 4 deep.
This is written to the page via a code block.
However, instead of returning a flat string from the method I would like to return it as formatted HTML, so when rendered it looks like this:
<ul>
<li>
<a href='default.aspx?param=1&anotherparam=2'>LINK</a>
</li>
</ul>
I thought about loading the html into an XmlDocument but it doesn't like the & character found in the query strings (in the href attribute values).
The main reason for doing this is so I can more easily debug the generated HTML during development.
Anyone have any ideas?

Maybe you can work with an HtmlTextWriter? It has Indenting capabilities and it may actually be a cleaner thing as you could write straight into the output stream, which should be more "in the flow" than generating a string in memory etc.

Is there a reason you want to do this? This implicitly minified HTML will perform slightly better anyway. If you do still need to render the HTML for pretty display, you will either need to incorporate indentation into the logic that generates the output HTML or build your content using ASP.NET controls and then call Render().

Try loading the HTML into the HTML Agilty Pack. It is an HTML parser that can deal with HTML fragments (and will be fine with & in URLs).
I am not sure if it can output pretty printed (what you call "formatted") HTML, but that would be my first approach.

I like to use format strings for this sort of thing, your HTML output would be generated with;
String.Format("<ul>{0}\t<li>{0}\t\t<a href='{2}'>{3}</a>{0}\t</li>{0}</ul>",
System.Environment.NewLine,
myHrefVariable,
myLinkText);

Related

Concatenation String - MVC Razor

With the Razor view engine, I just want to convert a path like this:
src="<%=MyImageServer %>image1.jpg"
into
src="#MyImageServer[PROBLEM_HERE]image1.jpg"
You see the problem... Any Suggestion?
Note: MyImageServer is a variable with a path.
Wrap in parentheses:
src="#(MyImageServer)image1.jpg"
But you probably want to avoid such tag soup in your views and write a custom HTML helper:
#Html.Image("image1.jpg")
which will take care of generating the proper image.

Trying to render two spaces between sentences in an HTML error message

I know that browsers strip out extra spaces after a single space. I generally use " " to include a second space between sentences in my HTML.
Anyway, I'm using ASP.NET MVC 3 and am trying to display an error message that's being injected into the page via a view model (as opposed to being coded directly into the HTML template). When I add " " to the error string that I'm putting into the view model, I end up getting "&nbsp;" in the resulting web page, I assume because MVC 3 HTML encodes the final rendering of the view.
Anyone know a way to get around this so that I can get back my beloved double spacing between sentences? :)
Thanks!
Use Html.Raw() in the view or change your view model from a string an HtmlString. Either way will bypass the HTML encoding. As long as you are sure this will be a "safe" string to render, it should be fine.

Formatting strings in ASP.NET Razor

I am currently writing a small templating system in ASP.NET to allow users to add content. For example, the user can enter the string (variable type is string).
topHeader[x] = "They think it's all over. It is now!";
However, one change that's needed is the ability to add some basic HTML tags within this content, so the following can be done
topHeader[x] = "They think it's all over. <strong>It is now!</strong>";
or
topHeader[x] = "They think it's all over. <a title="Football News" href="URL">It is now!</a>";
If you add such things into strings now they are not formatted as HTML, but I want to somehow escape them so that they can be. Naturally I've looked on the Internet for the answer, but as Razor is fairly new there's not much out there to help me out.
Anyone have an idea of how to do this?
You need to create an IHtmlString implementation holding your HTML source.
Razor plans to have a helper method to do this for you, but, AFAIK, it doesn't yet, so I believe you'll need to create your own class that implements the interface and returns your HTML from the GetHtmlString() method.
EDIT: You can use the HtmlString class.
You can either change your topHeader dictionary to hold IHtmlStrings instead of Strings, or you can leave your code as is, but wrap it in an HtmlString in the Razor view:
<tag>#new HtmlString(topHeader[x])</tag>
Make sure to correctly escape any non-HTML special characters.
The helper method they added is called Html.Raw() and it is much cleaner.
Here is an example:
#Html.Raw("Hello <a>World</a>!")
SLaks is right, but you don't need to write your own implementation of IHtmlString, there's one built in to System.Web called HtmlString. So:
topHeader[x] = new HtmlString("They think it's all over. <a title=\"Football News\" href=\"URL\">It is now!</a>");
Should do the trick.

asp.net MVC action link need to have the registered on the actual word

got this actionlink:
<%= Html.ActionLink("Corian® Worktops", "Index", "Corian")%>
the word corian has to carry the registered symbol or the word can not be used, but it seems to process, i know i could just write this as a normal href but it kinda defeats the object if there is another solution.
has any tried and successfully caried something like this out?
thanks
It works normally
<%= Html.ActionLink("RegistededMark®", "Action")%>
Use the normal ® symbol but make sure the font in HTML displays it correctly.
I do not know why but having static text in the views gives me the chills. I would rather suggest that you use a resource provider to fill in your link text. That way you will not be bothered by the html encoding stuff.

asp.net best practice string concatenation

I am trying to find the best practice for generating and outputting html which would require a database query first to obtain the info. Currently in the aspx page I have a div with runat server:
<div runat="server" id="leaflet"></div>
Now just as a start to do a bit of testing I have a method that runs on page_load that basically does:
private void BuildLeaflet(string qnid)
{
//gets leaflet details
QueryLeafletDetails();
//return concatenated content string
leaflet.InnerHtml "<h1>" + dr["LSC Descriptor"] + "</h1>";
}
In the real solution the return is a concatenation of about 10 fields some very long as they are content.
I don't by any means think this is the best solution, but what is? A StringBuilder? Can I Write Each Part in turn to the site avoiding the concatenation in the method? Is the server div even best?
Edit: Forgot to put some of my content sections have simple (limited) html in them already such as paragraph, list... This allows me to easily produce documents for web and printing, I just use different stylesheets.
I would use <asp:Literal runat="server" enableViewState="false" id="leaflet" />. This doesn't generate any tags on the page, and doesn't stuff all the text in the ViewState.
And yes, use StringBuilder if you need to concatenate many long strings. This will be way more memory efficient.
The other solution would be to see if you can make some fixed markup on the page and put the contents of each DB field in it's own control (<asp:Literal />?).
I'd use either string.Format, if the number of fields is fixed (and relatively small), or a StringBuilder, otherwise. Readability of the code would be my guide, less so performance. You might also want to think about abstracting this out into a UserControl if you plan to reuse it. Then you could give it settable properties and build the render logic into the control to avoid repeating yourself.
Various people have benchmarked this - iirc format is fine for <4 items, simple concats for <7, stringbuilding above that.
I strongly advise against creating HTML as strings btw.

Resources