2

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>
Teerth
  • 169
  • 3
  • 5
  • 19
  • 2
    Not possible. Razor code is parsed on the server before its sent to the view (a javascript variable is client side and does not exist on the server). You can use your script to update the `href` attribute of the generated `` tag –  Jun 09 '15 at 12:13
  • @StephenMuecke thats why I mentioned it in my question. Any idea how can I replace those – Teerth Jun 09 '15 at 12:25
  • What does your link currently generate - is it `../Export/1/2014-02-02/...` or `../Export?SelectedAccountType=1&FromDate=2014-02-02&...`? –  Jun 09 '15 at 12:31
  • @StephenMuecke yeah Sir it is genereating ../Export?SelectedAccountType=1&FromDate=2014-02-02&ToDate=2014-02-02" – Teerth Jun 09 '15 at 12:39
  • I can show you how to build the `href` attribute, but why are you not using form with `FormMethod.Get`? (no jquery would be required at all) –  Jun 09 '15 at 12:43
  • @StephenMuecke I haven't try that. Please have an example. To build that href – Teerth Jun 09 '15 at 13:06

1 Answers1

6

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