Any help with this would be much appreciated. I've got a datagrid and a download button on my UI. When the user selects a row in the grid and clicks download, it should pass the int id as parameter to my Download method on my controller, which triggers further processing.
I have tried using Ajax/JQuery for this, but alas I'm a novice and I keep getting 0 passed to controller. It is correctly selecting my id, as I have an alert which displays the correct id with each selection. I get no errors upon inspection in Chrome.
Please see relevant code below:
//html
<form asp-controller="Home" asp-action="Download" method="get">
<div id="downloadButton"></div>
</form>
//JQuery datagrid on my view:
$("#gridContainer2").dxDataGrid({
dataSource: DevExpress.data.AspNet.createStore({
loadUrl: url + "/GetLoadHistory",
key: "loadId"
}),
selection: {
mode: "single"
},
hoverStateEnabled: true,
paging: {
pageSize: 10
},
editing: {
mode: 'row',
},
onSelectionChanged: getLoadId
});
//JQuery functions with Ajax:
function getLoadId() {
var dataGrid = $("#gridContainer2").dxDataGrid("instance");
var loadId = dataGrid.getSelectedRowKeys();
console.log("Load ID: " + loadId);
download(loadId);
}
function download(loadId) {
$("#downloadButton").dxButton({
text: "Download Selected",
type: "normal",
icon: "/favicon.ico",
contentType: "application/json; charset=utf-8",
dataType: "json",
useSubmitBehavior: true,
onClick: function (e) {
$.ajax({
url: 'https://localhost:44346/home/Download/',
data: { LoadID: loadId}
}).done(function () {
DevExpress.ui.notify("Downloading results for Load ID: " + loadId, "info", 1500);
});
}
});
};
//download method on home controller:
[HttpGet]
public async Task<IActionResult> Download(int loadId)
{
//always 0...
Console.WriteLine("Load ID passed from UI:" + loadId);
//further processing
}
Try changing your jQuery.ajax
to the following:
$.ajax({
url: 'https://localhost:44346/home/Download/',
type: 'GET',
data: {
loadId: getLoadId()
}
}).done(function() {
DevExpress.ui.notify("Downloading results for Load ID: " + loadId, "info", 1500);
});
Note I've lowercased loadId
in the data you're sending to the server and explicitly stated that this is a HTTP GET request.
Edit: you weren't calling the getLoadId
function at all; the important line here is loadID: getLoadId()
. Confirm this by setting a breakpoint in getLoadId
in your browsers developer tools - I'm pretty sure without the above change that breakpoint won't be hit when you click your button.