文件名 return 空 ASP.NET 核心

Filename return null ASP.NET Core

我一直有问题 filename returns null in controller.There 没有关于如何解决这个问题的选项,我查看了整个互联网
屏幕:https://drive.google.com/file/d/1p6om2yBJ8sED_8DP0yB1AKEPYlcFXq_A/view?usp=sharing

][2]

        public int CategoryId { get; set; }

        [Required(ErrorMessage = "Enter category name")]
        [MaxLength(100, ErrorMessage = "MaxLength 100 symbols")]
        [MinLength(5, ErrorMessage = "MinLength 5 symbols")]
        public string CategoryName { get; set; }

        [Required(ErrorMessage = "Enter category description")]
        [MaxLength(500, ErrorMessage = "MaxLength 500 symbols")]
        [MinLength(100, ErrorMessage = "MaxLength 100 symbols")]
        public string CategoryDiscription { get; set; }

        public string FileName { get; set; }
        [NotMapped]
        public IFormFile File { get; set; }

    public async Task<ActionResult> Create([Bind("CategoryId","CategoryName","formFile")] CategoriesModel categories)
            {
                try
                {
                    string rootpatch = _webHostEnvironment.WebRootPath;
                    string filename = Path.GetFileNameWithoutExtension(categories.File.FileName);
                    string extension = Path.GetExtension(categories.File.FileName);
                    categories.FileName = filename + DateTime.Now.ToString("yy.MMM.dd") + extension;
                    string patch = Path.Combine(rootpatch + "/image/", filename);
    
                    using (var fileStream = new FileStream(patch, FileMode.Create))
                    {
                        await categories.File.CopyToAsync(fileStream);
                    }
    
                    _context.Add(categories); 
                    await _context.SaveChangesAsync();
                    return RedirectToAction();
                }
                catch
                {
                    return View();
                }
} 
        <form asp-action="Create" enctype="multipart/form-data">
        <div class="form-group">
            <label asp-for="File" class="control-label"></label>
            <input asp-for="File" class="form-control" type = "file"  accept = "image/*"/>
            <span asp-validation-for="File" class="text-danger"></span>
        </div> 
</form>  

 

你使用[Bind("CategoryId","CategoryName","formFile")],所以文件属性不会绑定到CategoriesModel categories。这里是官方doc关于绑定属性。

您可以尝试删除 [Bind("CategoryId","CategoryName","formFile")],并确保 Input 的名称在您看来是 File