How to use your Model property inside Javascript with Razor Pages

Suppose you want to display an alert if the property ‘Message’ of you model is not empty.
Here’s a practical example (with JQuery):


    <script>
        $(document).ready(function () {
            var msg = "@Html.Raw(Model.Message)";
            if (msg != "") {
                alert(msg);
            }
        });
    </script>

@Html.Raw(string) is used to avoid html escaping.

Leave a Reply

Your email address will not be published. Required fields are marked *