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?

5
  • stackoverflow.com/questions/5614941/… Commented Oct 11, 2013 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. Commented Oct 11, 2013 at 17:25
  • 2
    If this code block is placed inside <script> tags, it should work. Also you are missing quotes on msg Commented Oct 11, 2013 at 17:27
  • @user619656 can you explain more plz Commented Oct 11, 2013 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: <script> var msg="alert message"; alert(msg);</script>. Commented Oct 11, 2013 at 18:01

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.