简体   繁体   中英

Escape '@' character in Razor inside variable passed to javascript

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM