0

I have to pass email in variable to javascript. Something like this:

<button onclick="Send(email)">Send</button>

Obviously there is '@' character in email variable which I need to escape because I am getting this error: "Unexpected token ILLEGAL"

I read these posts: Escape @ character in razor view engine and Escape @ character in razor view engine but none of them resolve my problem. I don't know, what I am doing wrong.

There is almost everything what I tried with these posts:

<button onclick="Send(@email)">Send</button>

Result: as expected something@something.com => same error

{ 
 var str = email.Replace("@", ("@@"));
}
<button onclick="Send(@email)">Send</button>

Result: something@@something.com => same error

<button onclick="Send(@:@email)">Send</button>

Result: Server error: ":" is not valid at the start of a code block

{ 
 var str = email.Replace("@", "&#64;"));
}
<button onclick="Send(@email)">Send</button>

Result: something&64;something.com => Unexpected token ILLEGAL

<button onclick="Send(@(email))">Send</button>

or

<button onclick="Send(@(@email))">Send</button>

Result: as expected something@something.com => same error

<button onclick="Send(@@email)">Send</button>

Result: Close one. '@' is escaped and this is rendering onclick="@email", but unfortunately not inside the variable email.

I tried other various option but nothing worked.

<text></text>

and HttpUtility.Encode HttpUtility.JavascriptStringEncode HttpUtility.HtmlAttributeEncode Http.Raw does't seems to work either.

I will be glad for any advice. Really want to know what I am missing here. Thank you.

Community
  • 1
  • 1
Dávid M.
  • 130
  • 1
  • 6

1 Answers1

4

I think your issue is not one of Razor and instead JavaScript. It looks like you need quotes around @email because it is a string and JavaScript is complaining about the content without that because it is illegal.

<button onclick="Send('@email')">Send</button>
musicfuel
  • 1,532
  • 10
  • 7
  • Very nice. I knew it would be something so simple. I didn't realize that you need these '' here. Thank you very much. Worked! – Dávid M. Jan 09 '15 at 16:54