Pass a javascript variable as parameter to @url.Action()

人盡茶涼 提交于 2019-11-26 08:38:01

问题


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.

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

<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>

回答1:


You need to build you url using javascript/jquery. In the view change the link to

<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

@using (Html.BeginForm("Export", "yourControllerName", FormMethod.Get))
{
  @Html.TextBoxForm(m => m.SelectedAccountType)
  ....
  <input type="submit" value="Export" />
}


来源:https://stackoverflow.com/questions/30731582/pass-a-javascript-variable-as-parameter-to-url-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!