I have a problem all the time filename returns null in controller.There are no options for how to solve this, I reviewed the entire Internet
Screen: 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>
You use [Bind("CategoryId","CategoryName","formFile")]
,so the File property will not be binded to CategoriesModel categories
.Here is the official doc about Bind attribute.
You can try to remove [Bind("CategoryId","CategoryName","formFile")]
,and make sure the name of Input is File
in your view.