1

i have a javascript alert in C# code like this

if(Session["msg"] != null){
       string msg = (string)Session["msg"];
       if(msg.Length > 2) {
           @: var msg = @msg;
           @: alert(msg);
                               }

But in the view the alert doesn't appear:

result

The problem is that the alert message is written to the view.

Why does this happen? How can I fix this?

Community
  • 1
  • 1
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
  • http://stackoverflow.com/questions/5614941/mix-razor-and-javascript-code – Habib Oct 11 '13 at 17:24
  • 1
    It's doing some form of escaping. A lot of template languages do this by default. I don't know anying about C# or the razor framework, but it may be worth looking into the razor documentation... there are a ton of answers on here that solve this problem `@Html.Raw()` or something like that. – Dauh Fhauc Oct 11 '13 at 17:25
  • 2
    If this code block is placed inside – user619656 Oct 11 '13 at 17:27
  • @user619656 can you explain more plz – Lamloumi Afif Oct 11 '13 at 17:33
  • You can see the message in the view because is rendered as text inside/as html. What you want rendered by MVC is: . – user619656 Oct 11 '13 at 18:01

1 Answers1

3

You need to wrap the injected Razor string in quotes:

@: var msg = "@msg";

Let's say the content of "msg" is "Something" ... then, without the quotes, the rendered script would look like this:

var msg = Something

Which would be invalid, because there's no variable named "Something".

McGarnagle
  • 101,349
  • 31
  • 229
  • 260