将 javascript 变量作为参数传递给 @url.Action()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30731582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass a javascript variable as parameter to @url.Action()
提问by Teerth
is it possible to pass a javascript variable as a parameter to @url.Action(), because as far as i know there may be server and client side issue, my requirement is i have to download the file according to filter, and ajax call doesnot work with downloading the file. so i have harcode the @url.Action() that works but can not able to implement this, can anyone suggest me how to pass the parameter to @url.Action() or any other approach.
是否可以将javascript变量作为参数传递给@url.Action(),因为据我所知可能存在服务器端和客户端问题,我的要求是我必须根据过滤器和ajax调用下载文件不适用于下载文件。所以我对有效的@url.Action() 进行了编码,但无法实现这一点,谁能建议我如何将参数传递给@url.Action() 或任何其他方法。
here is my code
这是我的代码
<a href="@Url.Action("Export", new { SelectedAccountType="1", FromDate = "2014-02-02", ToDate = "2014-02-02", SelectedAccount = "", SelectedUser = "", SelectedTeam = "" })" class="btn-primary" id="exportbutton2"> Export as CSV</a>
and this is the parameter i want to assign to @Url.Action
这是我想分配给@Url.Action 的参数
<script type="text/javascript">
var accountType = $('#SelectedAccountType').val();
var fromDate = $('#FromDate').val();
var toDate = $('#ToDate').val();
var accountId = $('#SelectedAccount').val();
var userId = $('#SelectedUser').val();
var teamId = $('#SelectedTeam').val();
</script>
回答by
You need to build you url using javascript/jquery. In the view change the link to
您需要使用 javascript/jquery 构建您的 url。在视图中将链接更改为
<a id="export" href=#">Export as CSV</a>
Then in the script
然后在脚本中
var baseurl = '@Url.Action("Export")';
$('#export').click(function() {
var url = baseurl + '?SelectedAccountType=' + $('#SelectedAccountType').val() + '&FromDate=' + $('#FromDate').val() + '&ToDate=' + $('#ToDate').val() + ...etc
location.href=url;
});
However if your form is marked with FormMethod.Get
, then you can just use a normal submit button and no jquery is required
但是,如果您的表单标有FormMethod.Get
,那么您可以只使用普通的提交按钮,不需要 jquery
@using (Html.BeginForm("Export", "yourControllerName", FormMethod.Get))
{
@Html.TextBoxForm(m => m.SelectedAccountType)
....
<input type="submit" value="Export" />
}