asp.net mvc - convert javascript variable to C# variable - Stack Overflow

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

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>

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>
Share Improve this question edited Jan 18, 2020 at 1:17 Horai Nuri 5,57817 gold badges84 silver badges136 bronze badges asked Oct 13, 2011 at 8:23 learninglearning 11.7k36 gold badges89 silver badges156 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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>
}

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.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742271786a4412835.html

相关推荐

  • asp.net mvc - convert javascript variable to C# variable - Stack Overflow

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

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信