Amarundo
Amarundo

Reputation: 2397

How do I reference a Razor variable later in my page in JavaScript or HTML

I have the following Razor code:

@{
    if (IsPost)
    {
        string pn=Request.Form["pn"];
        if (!string.IsNullOrEmpty(pn)){
            /* my code to call the stored procedure with pn as a parameter*/
        }
    }
}

And in the page, using JavaScript / HTML I need to tell the user about pn. Be it that it's empty, or report back that the value was inserted in the database.

How do I do that?

Upvotes: 1

Views: 1201

Answers (1)

datadamnation
datadamnation

Reputation: 1892

You need to insert the result into the rendering. There are a couple of ways of doing that. You could store it in a variable:

<script type="text/javascript">
    var pn = '@(pn)';
    alert('pn is ' + pn);
</script>

Or you could call a function, sort of like JSONP:

<script type="text/javascript">
    parsePn('@(pn)');
    <!-- ... extra logic ...  --> 
    function parsePn(pn) {
        alert('pn is ' + pn);
    }
</script>

Upvotes: 4

Related Questions