【发布时间】:2021-12-12 18:12:04
【问题描述】:
我的视图中有一个表,它的行由 foreach 循环填充。该表的一部分如下:
@foreach (var item in Model.PmModel)
{
<td>@Html.DisplayName(item.pmNumber.ToString())</td>
<td>
<button type="button" class="btn btn-info btn-table btn-modal">Upload</button>
</td>
}
我在每一行都有一个按钮,通过按下每个按钮,会出现一个模式表单来上传文件。我使用以下代码上传文件并根据文件信息填充数据库列。但我需要将 pmId 从视图中移至以下操作:
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file != null)
{
if (file.Length > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(fileName);
var newFileName = string.Concat(Convert.ToString(Guid.NewGuid()), fileExtension);
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/PmFiles/UploadedByUsers", newFileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
var fileElements = new Models.FileRepository()
{
fileId = 0,
fileName = newFileName,
isDownloaded = false,
pm = _pmRepository.GetPmById(int Id), //I need to get Id from view
uploadDate = DateTime.Now,
};
_fileRepository.InsertFile(fileElements);
_fileRepository.SaveChanges();
}
}
return RedirectToAction("PmPage");
}
我使用 Bootstrap 模态:
@section Modal{
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"
dir="ltr">
<div class="modal-dialog">
<form method="post" enctype="multipart/form-data" asp-controller="Page" asp-action="UploadFile">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">File Upload</h5>
<button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row mt-2" dir="rtl">
<label class="form-label" for="customFile">Select your file:</label>
<input type="file" name="file" class="form-control" id="customFile" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-mdb-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger">Upload</button>
</div>
</div>
</form>
</div>
</div>
}
在视图中,我可以使用item.pmNumber 找到 pmId,但我不知道如何将它的值用于我的控制器。请帮帮我。
更新:此脚本通过按下按钮触发模式。
<script type="text/javascript">
$(document).ready(function () {
$('.btn-modal').click(function () {
$('#exampleModal').modal('show');
});
});
</script>
【问题讨论】:
-
您可以将视图中的 id 作为发布请求的一部分传递并获取它
public async Task<IActionResult> UploadFile(IFormFile file, int Id)您还可以创建将IFormFile和Id包装为属性的类a。跨度> -
您必须在调用上传操作的位置显示您的 javascript 和模式视图
-
@Serge 我更新了问题
-
谢谢,您打开此模式的代码在哪里?
-
@Serge 我更正了主要问题中的按钮类。请看一看。我用过 MDBootstrap
标签: asp.net-core-mvc