ASP.NET MVC中AJAX调用如何从视图传递所有文件的fileId参数
问题根源
你获取fileId始终为0是两个问题导致的:
- HTML 规范要求
id属性全局唯一,你循环渲染每行的隐藏<td>都用了id="fileId",$('#fileId')只会匹配到页面中第一个id为fileId的元素,不会拿到所有行的id <td>是普通DOM元素,没有value属性,你用.val()取值本身就会返回空值,转成数字就是0;另外你拼接URL时fileId=后面多了个空格,也会导致参数传值异常
修复步骤
第一步:修改表格渲染逻辑
给每行<tr>加上自定义data属性存储文件id,不需要额外写隐藏td,同时修正重复的downloads id为class:
<table id="files" class="table table-striped"> <thead> <tr> <th>Thumbnail</th> <th>Name</th> <th>Number of downloads</th> <th>Genre</th> <th>File Type</th> <th>Published On</th> <th>Created On</th> <th>Author</th> <th>Actions</th> </tr> </thead> <tbody> @foreach (var file in Model.Files) { var thumbPath = "~/Thumbnails/" + file.ThumbnailPath; <!-- 给行加data属性存文件id,避免重复id问题 --> <tr data-file-id="@file.Id"> <td><img style="width:80px;height:80px;" src="@thumbPath" asp-append-version="true" /></td> <td><a asp-controller="files" asp-action="details" asp-route-id="@file.Id" class="text-dark">@file.Name</a></td> <!-- 把id改成class,避免重复 --> <td class="downloads">@file.DownloadCounter</td> <td>@file.Genre.GenreName</td> <td>@file.FileT.FileTypeName</td> <td>@file.PublishedOn</td> <td>@file.Year</td> <td>@file.Author</td> <td> <a asp-controller="files" asp-action="QrCode" asp-route-id="@file.Id" class="btn btn-primary">Qr Code</a> <a asp-controller="files" asp-action="EditFile" asp-route-id="@file.Id" class="btn btn-primary">Edit</a> </td> </tr> } </tbody> </table>
第二步:修改AJAX逻辑
如果你的需求是选择日期后查询所有文件对应时间段的下载量,就遍历所有行拿到id数组传递给后端:
<script> $(document).ready(function () { $('#dateto').change(function () { var DateFrom = $('#datefrom').val(); var DateTo = $('#dateto').val(); // 遍历所有行收集文件id var fileIds = []; $('#files tbody tr').each(function() { fileIds.push($(this).data('file-id')); }); $.ajax({ type: 'GET', url: "Home/NumberDownloads", // 用data属性传参更规范,避免URL拼接错误 data: { dateFrom: DateFrom, dateTo: DateTo, fileIds: fileIds }, // 配置traditional让数组序列化格式符合ASP.NET MVC的参数解析规则 traditional: true, success: function (data) { console.log(data); // 如果你需要把返回的下载量更新到表格对应行,可以加这段逻辑 // data.forEach(item => { // $(`#files tbody tr[data-file-id="${item.fileId}"] .downloads`).text(item.downloadCount); // }) }, error: function (error) { console.log(error); } }); }); }); </script>
如果你的需求是查询单个文件的下载量,就不要把事件绑定在日期选择器上,改成绑定在每行的操作按钮上,点击时直接取当前行的$(this).closest('tr').data('file-id')即可拿到对应文件id。
内容的提问来源于stack exchange,提问作者viktorrr
相关产品推荐
相关产品推荐

