Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - Pass a javascript variable as parameter to @url.Action()

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" />
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...