在我的视图中,我有一个名为x:
的变量@{ int x;}
我想在jQuery代码中设置一个x值。
我该怎么做?
答案 0 :(得分:1)
由此:
@{var x = 5;}
<script type="text/javascript">
var c= @(x);
alert(c);
</script>
答案 1 :(得分:0)
只需使用@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>
答案 2 :(得分:0)
你可以做这样的事......
@{ // 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
}