Reputation: 897
In a situation when you do not need to pass any parameters below example works fine:
Controller without parameters:
[Authorize]
public ActionResult GetExcelTable()
{
XlWorkBook table = new XlWorkBook();
MemoryStream stream = new MemoryStream();
table.SaveAs(stream);
return File(stream, MyLib.MIMETypes.GetFileMIMEType(".xlsx"), "Kr-ti-" + Year + "-" + Month.ToString() + "_" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + ".xlsx");
}
Client:
<a href="@Url.Action("GetExcelTable", "Home")">Get excel</a>
But what if I want to pass some parameters to the controller and download the file? Is there anyway to simulate the click on a
tag from jquery and pass the parameters along. I know that you can not get the file with jquery ajax call.
Month
and Year
parameters are on the client side dynamic values that user specifies them in the dropdown list. I have to read this values before the controller is called and pass them to controller.
Controller with parameters:
[Authorize]
public ActionResult GetExcelTable(int Month, int Year)
{
XlWorkBook table = new XlWorkBook(Month, Year);
MemoryStream stream = new MemoryStream();
table.SaveAs(stream);
return File(stream, MyLib.MIMETypes.GetFileMIMEType(".xlsx"), "Kr-ti-" + Year + "-" + Month.ToString() + "_" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + ".xlsx");
}
Upvotes: 3
Views: 2320
Reputation: 12491
You can do it easily with one of overloads @Url.Action
that have routeValues
:
<a href="@Url.Action("GetExcelTable", "Home", new { Month = 9, Year = 2015})">Get excel</a>
If you want to pass them dynamicaly you should use Js, with Jquery it will be:
<a id="get-excel">Get excel</a>
<script>
$(document).ready(function () {
$(a#get-excel).click(function(){
var month = $(select#monthdd).val();
var year = $(select#yeardd).val();
window.location.href = '@Url.Action("GetExcelTable", "Home")?Month='+ month +'&Year=' + year;
});
});
<script/>
Upvotes: 2