0

i have issues alternating js and razor syntax.

i am trying to pass the value of a model variable to a javascript function, let's say something like this

<script>
    //this is my javascript function setTitle that simply changes the title 
    of a modal window, and i want to pass to it the title from the model
     ...
     setTitle(@Model.titleName);
     ...
</script>

so when i do this it doesn't work, and the script seems to break.

2 Answers 2

1

If it's a string you have to surround it with quotes.

setTitle('@Model.titleName');

If it's an integer you obviously don't need that.

In situations like these it's helpful to Right Click -> View Source, and take a look at the javascript it generated, and also report any errors the console window showed when asking a question.

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

Comments

1

You need to encase the Razor code in quotes so the result is a JavaScript string

setTitle("@Model.titleName");

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.