mixing html and C# - c#

I have some html that is going to be in every page so i stuck it in a .cs file. This piece of html has a lot of quotes so i would prefer not to escape each of the (\"). It isnt hard to since i can use find/replace but i wanted to know. Is there a nice way to mix html and CS so i can easily generate the page?

Rather than having your HTML in C# code move it to resource file. Here's how (for Visual Studio 2008):
Right-click on the project, select "Add New Item..."
Select Resource File. Leave Resource.resx as file name. A prompt will appear - select yes to place file in App_GlobalResources folder.
Double-click Resource.resx. Add new string item MyHtml.
In your code, use Resources.Resource.MyHtml:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Resources.Resource.MyHtml);
}
See also: How to: Create Resource Files for ASP.NET Web Sites

For the specific case of double quote, there's not a much better way. Generally, you can use verbatim strings. They will handle line breaks and all escape characters except " which should be replaced with "":
Response.Write(#"<html>
<body>
<h1 style=""style1"">Hello world</h1>
</body>
</html>");

Why wouldn't you just stick that HTML into a user control and then just add that user control to all the pages that use that HTML?

You say same html on EVERY page. Have you considered using a master page with a content placeholder for your common content? You could combine this with the user control idea mentioned by King Avitus.

You can use the legacy include directives in asp.net
You can then have your block of HTML in a separate .html file.
<!-- #include PathType = FileName -->

You could do this with single quotes:
string MyHTML = #"<html>
<body>
<div class='foo'>...</div>
</body>
</html>";
or do double double quotes:
string MyHTML = #"<html>
<body>
<div class=""foo"">...</div>
</body>
</html>";

If you use #string literals you can escape double quotes with 2 double quotes. Slightly more readable (but not much)...

You can use the # to treat it literally, or you can take a look at the HtmlTextWriter class for a more programmatic approach.

Related

format string containing html

I have a simple string variable that contains a portion of HTML inside. For example:
string contents = "<div><p>Hi how are you. Click here if you want to know more";
I want to include this HTML in page:
<div class="description">
#contents
</div>
However, it messes up the rest of the page because of unclosed tags.
Is there a function (or a helper) that reads and formats the HTML inside for example, to complete the HTML without errors:
#Html.DisplayProperHTML(contents)
This will render as:
<div><p>Hi how are you. Click here if you want to know more</p></div>
There is no such functionality built-in.
You can use the HTML Agility Pack to parse and fix broken HTML.

Regular expression to find anchor link with special href?

I just need to find a regular expression for the following:
I have some content in div tag, that includes lot of anchor links in it. So my task is to find anchor links with href as format of "components/showdoc.aspx?docid=" And then add onclick event for that anchor link only, leave the rest of the anchor links.
<div id="content" runat="server">
test doc
</div>
This expression gives and add target to it.
RegEx.Replace(inputString, "<(a)([^>]+)>", "<$1 target=""_blank""$2>")
Thanks
If you are looking to make permanent changes to your HTML file, first manage your HTML parsing by loading it into a System.Windows.Forms.WebBrowser control. From there you can perform DOM-like modifications to the HTML without the dangerous repercussions of parsing corruption that can be caused by performing Regex.Replace on the raw file. (Apparently RegEx + HTML is a serious issue for some).
So first in your code you would:
WebBrowser myBrowser = new WebBrowser();
myBrowser.URL = #"C:\MyPath\MyFile.HTML";
HtmlElement myDocBody = myBrowser.Document.Body;
Then you can navigate through your document body, seeking out your div tag and looking for your anchor tags by using the HtmlElement.Id property and HtmlElement.GetAttribute method.
Note: feel free to still use RegEx matching on the URL strings but only after extracting them from a GetAttribute("href") method.
To add the onClick method, simply invoke the HtmlElement.SetAttribute method.
When you have finished all your modifications, save the changes by writing the WebBrowser.DocumentText to file.
Here is a reference:
http://msdn.microsoft.com/en-us/library/system.windows.forms.htmlelement.aspx
Don't use regex to parse html, it's evil.
You could use the HTML Agility Pack, it even has a nice NuGet Package.
Alternatively, you could do this on the client side with a single line of jQuery:
$('a[href*="components/showdoc.aspx?docid="]').on('click', myClickFunction);
This is making use of the Attribute Contains Selector.
If you want to find the docid in your click function, you could write something like this in your click function:
function myClickFunction(e){
var href = $(this).attr('href');
var docId = href.split('=')[1];
alert(docId);
}
Note that this assumes there's only ever one query string value, if you wanted to make this more robust you could do something like in this answer: https://stackoverflow.com/a/1171731/21200

ASP.Net MVC: Localized texts with new line?

I've an Asp.Net MVC 3 website, which will be localized.
I've several resx files which contains my texts, and I've in my views some
#My.NameSpace.Through.My.LocalizationFile.Key
But I can't make it represent the new line.
I tried:
Shift+enter: I've got the new line in the resource file, but not in my browser
\r\n : I see the \r\n in my browser
\n : Same
<br/> : I see the <br/> in my text
So what should I do to have a new line?
Edit: I know that I could use Html.Raw, but I just can't ask to translators to put html code in their translation.
To be honest, I know it's not the nicest thing in the world, but it's fool-proof and it means your translators don't have to put any code in their translations:
Building upon the answers already given, why don't you just use Html.Raw, but before doing so, replacing the \r\n that using Shift+Enter in the resource file results in, with a <br />
So say for example you had the string named Welcome in the resource file ApplicationMessage, you could do:
#Html.Raw(ApplicationMessage.Welcome.Replace("\r\n", "<br />")
That will give you what you need. Here's a similar question:
HTMLencode HTMLdecode
You can put the <br /> for the line breaks and use the #Html.Raw() method to show the string with the line break instead of the <br /> string.
I think you should use a combination of Shift+Enter and the CSS white-space property instead of potentionally opening up to XSS vulnerabilities, as you would do using #Html.Raw() solution.
<span style="white-space: pre-line">#My.NameSpace.Through.My.LocalizationFile.Key</span>
I don't know the specific case, but it could be that you might find that pre-wrap suits your case better. Read more about the different white-space properties here
You should probably use <br /> and render the output with Html.Raw()
Yeah, thanks to mattytommo.
You can use
First line <br /> second line
in resource, or
resource.Replace("\r\n", "<br />")
in code and Shift + Enter in resource editor.
Both works fine, but you have to use
#Html.Raw();

How to find a matching closing tag in html string?

Imagine the following HTML:
<div>
<b></b>
<div>
<table>...</table>
</div>
</div> <!-- this one -->
...
How could I find the matching closing tag for the first opening div tag? Is there a reg ex that could find it? I guess this is quite a common requirement but I'm struggling to find anything straightforward, just full blown HTML parsers.
No.
Use a full blown HTML parser. There's a reason they exist.
Use Html Agility Pack.
I'm assuming that you have tokeinized the html tags... Now create a stack and every time you see an opening tag push and everytime you see a closing tag pop... and see if the ones you pop macth the closing tag...
But there are already HTML parsers for this so search for one on codeplex.
Well, You need to have a 'clear' view of the syntax ! However, regexp are very limited in scope and I would'nt recommand using it for multi-line/tag syntax.
You rather need to track each tag (open/close) and use a 'handler' to deal with your request. You could use some Lex/Yacc tools but this may be overkilling. Depending on the language you use, you may already have modules for this purpose (like HTMLParser in Python).
There's always LinqToXml if you want to parse HTML and don't need every little detail.

Render or convert Html to 'formatted' Text (.NET)

I'm importing some data from another test/bug tracking tool into tfs, and I would like to convert it's description, which is in simple HTML, so a plain string, where the 'layout' of the HTML is preserved.
For example:
<body>
<ol>
<li>Log on with user Acme & Co.</li>
<li>Navigate to the details tab</li>
<li>Check the official name</li>
</ol>
<br>
<br>
Expected Result:<br>
official name is filled in<br>
<br>
Actual Result:<br>
The &-sign is not shown correctly<br>
See attachement.
</body>
Would become plain text with newlines inserted and HTML-entities translated like:
1. Log on with user Acme & Co.
2. Navigate to the details tab
3. Check the official name
Expected Result:
official name is filled in
Actual Result:
The &-sign is not shown correctly
See attachment
I can currently replace some tags with newlines using a regex and strip the rest, but replacing the HTML-entities and stuff like <ol> and <ul> seemed like I'm re-inventing something (browser?). So I was wondering if someone has done this before me. I can't find it using Google.
Rather than regex, you could try loading it into the HTML agility pack? If it was xhtml, then an xslt transformation might be a good option.
In the end, once I got more comfortable with TFS, I customized the work item type to include a new HTML Field, and just copied the contents into that field.
This solution was so much better, because we could now see the intended formatting of the field.

Categories