-1

I am using ASP MVC 4 and jQuery. I want to get ViewModel properties from the javascript. I tried some solutions from stackoverflow, but none of them was working for me. Hope you Help me.

Thanks

7
  • You have you to have you javascript in your razor file to do this. Do you have yours in your razor file? This link should help stackoverflow.com/questions/21391402/… Commented Aug 3, 2017 at 16:03
  • I am trying to access to view model from external js file. Commented Aug 3, 2017 at 16:06
  • This is not possible. The only way around this is to declare a global JavaScript variable in the razor file from the model and use that variable from you external js file. Commented Aug 3, 2017 at 16:07
  • Is your view a strongly typed? Commented Aug 3, 2017 at 16:11
  • Can you please give me exact steps or useful links? @Derek Commented Aug 3, 2017 at 16:15

1 Answer 1

1

You can not access model properties from external JavaScript files so you have two options. You can include all of your JavaScript in the razor file as seen in the link below.

access model in javascript asp .net mvc razor

Otherwise you can set a global JavaScript variable and use it in your external file as seen below.

razor.cshtml

@model Order
<script>
    var isEdit = '@Model.IsEditable'
</script>

externalfile.js

function getEdit() {
alert(isEdit);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you @Derek You saved me much time. Thanks again
No problem I am just glad we got you moving forward!

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.