Formatting strings in ASP.NET Razor - asp.net

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.

Related

ASP.NET MVC2 Not replacing underscores with dashes in HtmlAttributes

I've heard from a couple of different sources that when using HTML helpers in ASP.NET MVC2, one can create custom attributes with dashes in them (e.g. <a data-rowId="5">) by using an underscore in place of the dash, and when the HTML is written to the page the underscores will be replaced by dashes.
So, something like this:
<%= HtmlActionLink(Model.Name, "MyView", null, new {data_rowId = Model.id}) %>
should render as
<a data-rowId="0" href="myURL">Row Name</a>
But... it's not. I think that maybe this feature is only enabled in the MVC3 Beta preview (as it's mentioned in the MVC3 preview release notes), but this thread is about the same thing, and it's regarding MVC2.
I know I can use the other solution presented in that thread, but I'd rather not have to resort to using the dictionary if a more elegant solution exists.
Anyone know if there's something simple I can do to get this particular thing working?
Not exactly the most elegant solution but probably acceptable:
<%= Html.ActionLink(
Model.Name,
"MyView",
null,
new Dictionary<string, string> { { "data-rowId", Model.id } }
) %>
On a side note: data-rowId is a totally invalid attribute in HTML according to standard doctypes so maybe the most elegant solution would be to get rid of it :-)
System.Web.Mvc.HtmlHelper provides a static method that does what you're looking for:
<%= Html.ActionLink(
Model.Name,
"MyView",
null,
HtmlHelper.AnonymousObjectToHtmlAttributes(new { data_row_id: Model.id })
) %>
This method will will substitute underscores with hyphens - as somebody pointed out though, be sure to use all-lowercase attribute names, which are HTML5-compliant.
Consider what ASP.NET MVC is designed to do. It is designed to give you tight control over the HTML that you produce. If something is not accessible, you won't have to jump through hoops to fix it. What you are trying to do is create invalid HTML, or XHTML. Instead of trying to make HTML that is invalid simplify to just using an ID. #1 on the accessibility guidelines is that the HTML is valid for the declared type.
As long as the ID is unique within the document you will have satisfied HTML conformance--and it will make it much easier to manipulate with jQuery.
If I may, why are you trying to create invalid HTML? Or is this a proprietary XML format?
BTW, MVC 3 RC came out today.
Edit:
Playing with HTML5 features, while "shiny" and kool, are unstable. Many parts of the specification are changing as often as weekly. What is considered good now may not be good when the final spec is released. MVC 3 does have some things that will make your job more friendly, for now you have to use a dictionary.

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.

Easy Way to Change Style of Cents in Money Text

I have a label (literal, whatever), that is being filled with currency ($5000.00). Is there an easy way to style the cents, like make the font-size smaller.
I know I can split the two up, but I am using MVP, and am looking for an easy way than passing all these new properties to the control (4+ of these labels are present).
Open to any suggestions, like a new control instead of the label, whatever you got.
I would suggest creating a new control that simply extends to Label/Literal. You can call it MoneyLabel, though Literal would probably be easier to work with. From that point, you can override the Render method to change the HTML output, format the string as you like.
Referencing it is not that tricky, the pages would need to reference the assembly where the class is stored.
In this way, you are not introducing CSS and HTML from the codebehind, not having to create extra JavaScript from what you need, and this is extremely reusable and its into how you code .NET already
I suppose in an ideally semantic world you'd probably do something like:-
<span class="currency-symbol">£</span>
<span class="major-currency-unit">5000</span>
<span class="decimal-point">.</span>
<span class="minor-currency-unit">00</span>
and then style away to your heart's content.
I would inherit from the label class, then create a newlabel class, StyledMoneyLabel.
I haven't tested this code, but hopefully you'll get the idea.
class StyledMoneyLabel : Label
{
double money = 0.0;
Render(HtmltextWriter)
{
HtmlSpan dollars = new HtmlSpan(CSS_CLASS);
dollars.Text = money.ToString(FORMAT_STRING_FOR_GETTING_DOLLARS.
///etc for decimals and so forth
}
}
Ideally you need to format it like the following.
$5000.<span class="Cents">00</span>
How you accomplish this is a bit tricky, you can have a "Dollars" and a "Cents" property and then manipulate the string into the format.
You could use javascript and let the client do all the heavy lifting...eg, in jquery (you'd have to define the putSpansAroundDollarsAndCents() function)
<div class="currencyToSplit">$5000.00</div>
$(".currencyToSplit").each(function() { putSpansAroundDollarsAndCents($(this)) });

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.

How to deal with special characters in ASP.NET's HyperLink.NavigateUrl?

I am currently having troubles figuring out how to handle a filepath to be (dynamicly) passed out to a HyperLink control's NavigateUrl property.
Let's say that I'm trying to refer to a file named jäynä.txt at the root of C:.
Passing "file:///C:/jäynä.txt" result to a link to file:///C:/jäynä.txt, as does HttpUtility.UrlPathEncode("file:///C:/jäynä.txt").
Replacing the ä**s with **%E4, which gives the string "file:///C:/j%E4yn%E4.txt", does give a working link to file:///C:/jäynä.txt, but I have not been able to find a way to make the replacement without defining it myself. With Replace("ä", "%E4"), for example.
Is there a way to automaticly handle the filepath string so that the HyperLink would display it correctly, without manualy listing what characters to replace in the string?
Additional Note:
There may be a way to work around this by spesifying the character encoding in which the page is rendered, because debugging shows that the HyperLink at least saves the string "file:///C:/jäynä.txt" unchanged, but somehow mangles it around the time of rendering.
However, this seems only be the case in rendering of the NavigateUrl because other components as well as HyperLink's Text-property are all quite capable of rendering the character ä unchanged.
The NavigateUrl property of a Hyperlink will encode unicode chars in the url.
Instead you can set the href attribute property of the Hyperlink like this:
hyperlink1.Attribute("href") = "file:///C:/jäynä.txt"
This is due to how the browser starts to interpret the path, typically individuals will avoid using characters such as that in the urls of pages.
In your case, I believe you have struck upon the best case scenario, as I am not aware of any way to change the behavior of HttpUtility and/or the NavigateUrl property. At least not without creating a custom control for it.
Don't use HyperLink control. Instead use HtmlAnchor control. It will solve your problem. I don't know why Microsoft designed like this.
Thank you!
The post using the 'attributes' solved my problem. In my case it was
HyperLink6.Attributes["href"] = "http://høgstedt.danquah.dk/";
The problem of using special danish characters in a url seem to have been troubling a lot of programmers - a search provides several very complicated approaches. This one is SIMPLE and it SIMPLY WORKS.
So once again, thank you

Resources