1

Is it possible to initialize a variable in view using razor and then manipulate the value of it using jquery or vice versa?

1 Answer 1

4

Yes,

If you are in a .cshtml view you can do something like this:

<script type="text/javascript">
  var test = '@Model.Variable';

  $("#element").val(test);
</script>

But I am not sure if there is a way to pass a JS variable to Razor code, I don't think so. But you could maybe make an ajax call and pass the JS value.

<script type="text/javascript">
  var val = $("element").val();

  $.ajax({
     url: '/controller/action',
     data: { id: val },
     success: function(result) {
     // Do something with the ajax call result here
   }
  });
</script>

There is also a nice open source project called RazorJS, you should check it out

http://john.katsiotis.com/blog/razorjs---write-razor-inside-your-javascript-files

Sign up to request clarification or add additional context in comments.

Comments

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.