Jimmyt1988
Jimmyt1988

Reputation: 21146

escaping/encoding characters ready for use in an attribute

Context:

I want to pass a title field into an Angular attribute. The title field is sometimes crazy with the characters people put in.

I have the following Csharp property:

Model.StoryTitle = "!"£$%^&*()<>;><~andanythingelsethatisweird";

<my-directive-thing story-title="@Model.StoryTitle"></my-directive-thing>

I also have this on a page that pulls the same field out of an Ajax call and gets populated by Kendo (darn legacy frameworks):

<my-directive-thing story-title="#= storyTitle #"></my-directive-thing>

On my directive side, I have the following code:

var storyTitle = $attrs.storyTitle || "";

Issue:

Due to the issue of having weird characters sometimes, I decided to escape it on the javascript side:

<my-directive-thing story-title="#= escape(storyTitle) #"></my-directive-thing>

The job was then easy as I put an unescape in the directive:

var storyTitle = unescape($attrs.storyTitle) || "";

Then everything works fine.

However, I don't know an equivalent for the Csharp.

Question:

Is there a trick I'm missing on the JavaScript + Csharp way of making sure ugly characters don't break attributes?

Upvotes: 2

Views: 73

Answers (1)

lin
lin

Reputation: 18392

Escape those characters or transform those characters to HTML enteties. You should not do that on your client side. Your backend should deliver nice encoded/decoded data.

Model.StoryTitle = HttpUtility.HtmlDecode("!"£$%^&*()<>;><~andanythingelsethatisweird");

> HttpUtility.HtmlDecode() documentation

Upvotes: 1

Related Questions