user1765862
user1765862

Reputation: 14145

access to model.Id on razor view page from javascript

on view page I have and inside javascript code I want to access to my Model.Id. How this can be done?

@model MyModel
<script type="text/javascript">
    function initialize() {
       var id = model.Id // this doesnt work
    }
</script>

Thanks

Upvotes: 0

Views: 1708

Answers (3)

Jack
Jack

Reputation: 8941

This should work. Still need to use the razor syntax..@.

@model MyModel
<script type="text/javascript">
    function initialize() {
       var id = "@Model.Id" // this doesnt work
    }
</script>

Upvotes: 1

Jason
Jason

Reputation: 15931

You need to keep track of what's on the server and what's on the client. The @Model variable is only used on the server, Javascript has no notion of the model object, so you need to print the values out in the html.

<script type="text/javascript">
    function initialize() {
       var id = "@Model.Id"; // this will work
    }
</script>

Upvotes: 2

jishnu saha
jishnu saha

Reputation: 165

Make model.id to "@Model.id" Like :

@model MyModel
<script type="text/javascript">
function initialize() {
   var id = "@Model.Id"
}
</script>

Upvotes: 1

Related Questions