0

I want to use a javascript variable to pass as a parameter to my class constructor in C#.

How can I translate the javascript variable ID to C# such that I am able to pass the value on User.IsOnLeave?

<script type="text/javascript">
  var ID;
  var dateToEvaluate;

  function convertVariable() {
    *if (User.IsOnLeave(***ID***, dateToEvaluate)) {...}*
  }
</script>

3 Answers 3

5

You can't access JS variables directly from C#, because JS is client-side and C# is server-side. You can make a controller action and make an AJAX request to it with those parameters. Like this:

JS:

var id;
var dataToEvaluate;

jQuery.ajax({
    type: 'POST',
    url: 'SomeController/SomeAction',
    data: { id: id, dataToEvaluate: dataToEvaluate },
    success: function(data) {
        // do what you have to do with the result of the action
    }
});

controller:

public ActionResult SomeAction(string id, string dataToEvaluate)
{
     // some processing here
     return <probably a JsonResult or something that fits your needs>
}
Sign up to request clarification or add additional context in comments.

Comments

0

One of the way (IMO, the only way) of working with your C# code inside your JavaScript code is to make Ajax calls.

jQuery.ajax() is a good choice.

Comments

0

The easiest option is to just render the value to a hidden textbox or dom element, then have javascript access the field.

For example

<input type="hidden" value="set from c#" id="myValue" />

in javascript

var dateToEvaluate = document.getElemenetById("myValue").value;

Or if you Javascript is in the same file as your HTML. You could just say in javascript:

var dateToEvaluate = @myValue;

assuming razor syntax

2 Comments

why the down vote? Similar answer here stackoverflow.com/questions/4599169/… has over 177 up votes
I would assume it's because the OP is trying to get a JS value into C# code, and not the other way around as you have demonstrated.

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.