0

I'm using Asp.Net Core and trying to reference the model from inside a script tag:

<div>
    <script>
        function calcprices() {                                                
            @Model.Price = document.getElementById("price").value;
        }
    </script>

    <button onclick="calcprices()">Recalculate</button>

The error showing in console window is:

ReferenceError: calcprices is not defined

If I have a look at the debugger, it shows the particular section is missing the Model reference:

function calcprices() {                                                
     = document.getElementById("price").value;
}

So I'm guessing that's why I'm getting an error. Is it not possible to reference a model like this?

  • You can't. `@Model.Price` runs serverside – adiga Dec 23 '19 at 15:50
  • Does this answer your question? [Accessing MVC's model property from Javascript](https://stackoverflow.com/questions/16361364/accessing-mvcs-model-property-from-javascript) – Eric Lease Dec 23 '19 at 16:11

1 Answers1

0

It's not possible to reference your model that way. In Razor, the C# and @Model.x elements are executed as the page is run and outputs are rendered as plain text.

If your @model.Price had a value (say 10 for example) it would be rendered on screen like this:

function calcprices() {                                                
    10 = document.getElementById("price").value;
}

You can use them as static values in your javascript (something we've made extensive use of) but you cannot address them as objects.

I'd suggest, if you're trying to update an object in session, use ajax to call a JsonResult method, post your data and return the output in the Json result.

Stuart Frankish
  • 818
  • 1
  • 11
  • 27