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>
Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
learning
  • 11,415
  • 35
  • 87
  • 154

3 Answers3

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>
}
devnull
  • 2,790
  • 22
  • 25
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.

tugberk
  • 57,477
  • 67
  • 243
  • 335
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

Daveo
  • 19,018
  • 10
  • 48
  • 71
  • why the down vote? Similar answer here http://stackoverflow.com/questions/4599169/using-razor-within-javascript/4599403#4599403 has over 177 up votes – Daveo Aug 08 '13 at 05:43
  • 1
    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. – Citrus Jul 18 '14 at 05:53