Reputation: 11745
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>
Upvotes: 0
Views: 10830
Reputation: 19912
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
Upvotes: 0
Reputation: 2860
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>
}
Upvotes: 5
Reputation: 58494
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.
Upvotes: 0