【发布时间】:2021-09-19 11:27:39
【问题描述】:
我有这个模型,并且表 i db 有数据
public class FileType
{
public int Id { get; set; }
public string FileTypeName { get; set; }
}
我有上传表单和这个视图模型供上传
public List<FileModel> Files { get; set; }
public string Name { get; set; }
public string Extension { get; set; }
public string Description { get; set; }
public string Author { get; set; }
public string Year { get; set; }
public string FilePath { get; set; }
public string PublishedOn { get; set; }
public int DownloadCounter { get; set; }
public Genres Genre { get; set;}
public int FileTypeId { get; set; }
public List<SelectListItem> FtypeList { get; set; }
public FileType FileT { get; set; }
我使用此代码生成下拉列表以选择 FileType:
public IActionResult Index()
{
var vm = new FileUploadViewModel();
vm.FtypeList = context.FileTypes
.Select(a => new SelectListItem()
{
Value = a.Id.ToString(),
Text=a.FileTypeName
}).ToList();
ViewBag.Message = TempData["Message"];
return View(vm);
}
我认为我有这个
<div class="form-group row">
<label asp-for="FileT" class="col-sm-2 col-form-label"> </label>
<div class="col-sm-10">
<select asp-for="FileT" class="custom-select mr-sm-2" asp-items="@Model.FtypeList"></select>
</div>
</div>
在 HttpPost 操作中我这样做
[HttpPost]
public async Task<IActionResult> Index(List<IFormFile> files, string description,DateTime PublishedOn,string Author,string Name,FileType Ftype)
{
foreach (var file in files)
{
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\Files\\");
bool basePathExists = System.IO.Directory.Exists(basePath);
if (!basePathExists) Directory.CreateDirectory(basePath);
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var filePath = Path.Combine(basePath, file.FileName);
var extension = Path.GetExtension(file.FileName);
DateTime dateTime = DateTime.UtcNow;
var createdOn = dateTime.ToShortDateString();
if (!System.IO.File.Exists(filePath))
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
var fileModel = new FileModel
{
Year =createdOn,
PublishedOn = PublishedOn.ToShortDateString(),
FileType = file.ContentType,
Extension = extension,
Name = Name,
Description = description,
FilePath = filePath,
Author=Author,
Ftype=Ftype,
};
context.Files.Add(fileModel);
context.SaveChanges();
}
}
TempData["Message"] = "File successfully uploaded to File System.";
return RedirectToAction("Index","Home");
}
但是当我上传文件时,它不会从下拉列表中获取选定的值,它会在选定的列表中创建新项目。例如,如果我在文件上传到数据库时选择值为 3 的项目,则表中只有 4 个文件类型上传文件 Ftype = 5 的表,并在 Id = 5 的 FileTypes 表中创建新行。
【问题讨论】:
-
我不清楚您从视图中摘录的内容与发布操作有何关联。在您的代码中,您使用
asp-for="FileT",这意味着将发送名称为FileT的表单数据(这将是一个int,因为您使用FileType.Id作为值)。但在行动中,你期待的是FileType FType。 -
我有一个名为 FileModel 的主模型,我在这里传递 context.Files.Add(fileModel);所以在那个模型中,我想从下拉列表中保存选定的 FileType 及其公共 FileType Ftype。它应该是 int FtypeID 而不是 FileType Ftype 并在 post 方法中像整数一样保存它?
标签: c# asp.net asp.net-mvc postgresql asp.net-core