Home > Software engineering >  IFormFile is always null in ASP.NET Core 3.1 MVC
IFormFile is always null in ASP.NET Core 3.1 MVC

Time:04-20

I have been sitting at my desk for several days, reading through Google searches, trying to get my ASP.Net Core application to upload files to physical location, and store the filename in the database. However whenever I try to upload a file, the IFormFile always returns a null. I'm fairly new to this.

Here is the view code

<div >
    <form method="post" enctype="multipart/form-data" asp-controller="Quiz" asp-action="Create"  >
        <div asp-validation-summary="ModelOnly" ></div>
        
        <div >
            <label asp-for="QuizTitle" ></label>
            <input asp-for="QuizTitle"  />
            <span asp-validation-for="QuizTitle" ></span>
        </div>
        <div >
            <label asp-for="Category" ></label>
            <input asp-for="Category"  />
            <span asp-validation-for="Category" ></span>
        </div>
        <div >
            <label asp-for="Author" ></label>
            <input asp-for="Author"  />
            <span asp-validation-for="Author" ></span>
        </div>
        <div >
            <label asp-for="QuizPdf" ></label>
            <input asp-for="QuizPdf" >
            <span asp-validation-for="QuizPdf" ></span>
            </div>
        
        <div >
            <input type="submit" value="Create"  />
        </div>
    </form>

The controller code

public IActionResult Create()
    {
        return View();
    }

    // POST: Quiz/Create
    // To protect from overposting attacks, enable the specific properties you want to bind to.
    // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]

    public async Task<IActionResult> Create([FromForm]IFormFile PostedFile, QuizDetailsModel quizDetailsModel)
    {
        if (ModelState.IsValid)
        {
            if (quizDetailsModel.QuizPdf != null)
            {
                string folder = "files/pdfs/";
                folder  = quizDetailsModel.QuizPdf.FileName;

                quizDetailsModel.QuizPdfUrl = folder;

                string serverFolder = Path.Combine(_webHostEnvironment.WebRootPath, folder);

                await quizDetailsModel.QuizPdf.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
            }
            _context.Add(quizDetailsModel);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(quizDetailsModel);
    }

and the model code

public class QuizDetailsModel
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Please enter a quiz title.")]
    [Display(Name = "Title")]
    public string QuizTitle { get; set; }
    [Required(ErrorMessage = "Please select a category.")]
    public string Category { get; set; }
    [Required(ErrorMessage = "Please enter a quiz author")]
    public string Author { get; set; }
    [Display(Name = "Upload quiz pdf.")]
    [Required]
    [NotMapped]
    public IFormFile? QuizPdf { get; set; }
    public string QuizPdfUrl { get; set; }
    [Display(Name = "Date Added")]
    [DisplayFormat(DataFormatString = "{0:MMMM dd, yyyy")]
    [DataType(DataType.Date)]
    public DateTime DateAdded { get; set; } = DateTime.Now;

    public List<QuestionsAnswersModel> QuestionsAnswers { get; set; } = new List<QuestionsAnswersModel>();

enter image description here

Option 2: In create view , add type="file", method="post" enctype="multipart/form-data"

      <form asp-action="Create"  method="post" enctype="multipart/form-data" >
            <div asp-validation-summary="ModelOnly" ></div>
                ...
            <div >
                <label asp-for="QuizPdf" ></label>
                <input asp-for="QuizPdf" type="file" />
                <span asp-validation-for="QuizPdf" ></span>
            </div>
                   ...
             <div >
                <input type="submit" value="Create"  />
            </div>
        </form>

result: enter image description here

  • Related