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>
6
  • 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 <a> tag Commented Jun 9, 2015 at 12:13
  • @StephenMuecke thats why I mentioned it in my question. Any idea how can I replace those Commented Jun 9, 2015 at 12:25
  • What does your link currently generate - is it ../Export/1/2014-02-02/... or ../Export?SelectedAccountType=1&FromDate=2014-02-02&...? Commented Jun 9, 2015 at 12:31
  • @StephenMuecke yeah Sir it is genereating ../Export?SelectedAccountType=1&amp;FromDate=2014-02-02&amp;ToDate=2014-02-02" Commented Jun 9, 2015 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) Commented Jun 9, 2015 at 12:43

1 Answer 1

7

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" />
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.