Javascript 如何从jQuery向MVC3视图中的变量传递变量?
可能重复:Javascript 如何从jQuery向MVC3视图中的变量传递变量?,javascript,jquery,asp.net-mvc-3,Javascript,Jquery,Asp.net Mvc 3,可能重复: 在我看来,我有一个名为x的变量,如下所示: @{ int x;} 我想在jQuery代码中设置一个x值 我该怎么做?通过以下方式: @{var x = 5;} <script type="text/javascript"> var c= @(x); alert(c); </script> @{var x=5;} var c=@(x); 警报(c); 只需使用@x即可获得值。前 @{int x = 42;} <script typ
在我看来,我有一个名为x的变量,如下所示:
@{ int x;}
我想在jQuery代码中设置一个x值
我该怎么做?通过以下方式:
@{var x = 5;}
<script type="text/javascript">
var c= @(x);
alert(c);
</script>
@{var x=5;}
var c=@(x);
警报(c);
只需使用@x
即可获得值。前
@{int x = 42;}
<script type="text/javascript"> var x = @(x); alert('The answer to the Ultimate Question of Life, the Universe, and Everything is ' + x); </script>
@{int x=42;}
var x=@(x);警惕(“生命、宇宙和万物的终极问题的答案是“+x”);
您可以这样做
@{ // declare this in your view
int x = 100;
}
$(document).ready(function() {
var postdata = @x + 100; // here is the updated code. if you want to change the value eg. this will alert 200
alert(postdata);
$.ajax({
url: 'Home/Index',
data: postdata,
success: function (returnData) {
alert(returnData); // this will alert 210
}
});
});
你的控制器
public ActionResult Index(int x) // x will get the value here which is 200 here now..
{
var y = x + 10; // do some logic here with the posted data from your view
return Json(y,JsonRequestBehaviour.AllowGet); // you will need to return Json here cos you using the AJAX call
}
请更详细地解释你的问题。听起来他是在另一个方向。谢谢你的快速回答,但我想做的是相反的,@(x)=5好的,js是一个客户端代码,只在浏览器上运行。因此,你可以使用下面的链接@Darin评论Q.问候。对不起,我的英语很差,在我的脚本中,我需要更改x变量,以便在ActionLink中使用它,如