C# 使用JQuery(MVC)在razor视图中填充全局变量
请参阅下面的代码:C# 使用JQuery(MVC)在razor视图中填充全局变量,c#,jquery,asp.net-mvc,razor,C#,Jquery,Asp.net Mvc,Razor,请参阅下面的代码: @{ var propertyList = new List<Tuple<string, string>>(); } <input type="text" data-id="@item.Item1" class="form-control prop"/> <a class="btn btn-default" id="run-report" href="@Url.Action("RunReport", "Reports",
@{
var propertyList = new List<Tuple<string, string>>();
}
<input type="text" data-id="@item.Item1" class="form-control prop"/>
<a class="btn btn-default" id="run-report" href="@Url.Action("RunReport", "Reports", new {reportId = Model.ReportId, propList = propertyList})"> Run Report</a>
<script>
$("#run-report").click(function () {
$(".prop").each(function () {
var currentProp = $(this).attr("data-id");
var currentPropVal = (this).value;
@{
propertyList.Add(new Tuple<string, string>("", ""));
}
});
});
</script>
@{
var propertyList=新列表();
}
$(“#运行报告”)。单击(函数(){
$(“.prop”)。每个(函数(){
var currentProp=$(this.attr(“数据id”);
var currentPropVal=(this).value;
@{
添加(新元组(“,”);
}
});
});
正如您在上面看到的,我有一个名为propertyList
的全局变量,它包含一个元组列表,
我在这里声明这一点是因为我需要使用Url.Action
从我的控制器操作将报告直接下载到浏览器
当我从文本框中获取值时,我遇到了一些麻烦。我需要将jQuery中的值添加到元组的全局列表中
看来我不能这样做
任何建议都将不胜感激
谢谢记住,
@{}
代码在服务器端运行,所以在它进入浏览器之前。一旦它在浏览器中“呈现”,就好像它是纯文本,无法更改
可以通过在脚本中构建参数来传递参数,例如:
从Url.Action参数中删除参数
<input type="text" data-id="@item.Item1" class="form-control prop"/>
<a class="btn btn-default" id="run-report" href="@Url.Action("RunReport", "Reports", new {reportId = Model.ReportId})"> Run Report</a>
根据您的操作预期的格式,您可能需要更改url的构建方式,但这说明了原则。您混合了客户端和服务器端代码。服务器端代码
@{}
在到达浏览器之前运行,之后无法更改。考虑到Razor首先在服务器中编译,然后在浏览器中执行jQuery。。。
$("#run-report").click(function () {
var url = $(this).attr("href");
$(".prop").each(function () {
var currentProp = $(this).data("id");
var currentPropVal = (this).value;
url += "?" + currentProp + "=" + currentPropVal;
});
location.href = url;
});