将javascript变量转换为C#变量

lea*_*ing 0 javascript asp.net-mvc

我想使用一个javascript变量作为参数传递给我在C#中的类构造函数.

如何将jaascript变量ID转换为C#,以便我能够在User.IsOnLeave上传递值?

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

function convertVariable()
    {


 *if (User.IsOnLeave(***ID***, dateToEvaluate))
            {

}*
}
</script>
Run Code Online (Sandbox Code Playgroud)

dev*_*ull 5

您不能直接从C#访问JS变量,因为JS是客户端的,C#是服务器端的.您可以使用这些参数进行控制器操作并向其发出AJAX请求.像这样:

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
    }
});
Run Code Online (Sandbox Code Playgroud)

控制器:

public ActionResult SomeAction(string id, string dataToEvaluate)
{
     // some processing here
     return <probably a JsonResult or something that fits your needs>
}
Run Code Online (Sandbox Code Playgroud)