0

I have an ASP.NET MVC app attempting to upload an IFormFile. The uploaded file is accessible in the controller but after redirecting from the controller.

I need to display the previously attached file and other form errors if there are any.

How can we display or hold the attached file if there is a model error.

Controller:

public IActionResult AddEmployee(Employee model)
{
    // Do validation for Employee model 

    if (!ModelState.IsValid)
    {
        return View("Add", model);
    }

    return View("View");
}

.cshtml view:

<form method="post" encType="multipart/form-data">
    <!-- /.row -->
    <div class="row">
        <div class="col-sm-5 col-md-6">
            <div class="form-group">
                <label> Attachment</label>
                <input Name="Attachment" id="Attachment" Type="file" accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.bmp,.tiff,.pdf,.msg,.zip" style="font-weight:normal;">
            </div>
        </div>
    </div>
    <!-- /.col-lg-12 -->
</form>

Model class:

public class Employee
{
    public IFormFile Attachment { get; set; }
}
Qing Guo
  • 6,041
  • 1
  • 2
  • 10
Balanjaneyulu K
  • 3,660
  • 5
  • 24
  • 45
  • in case the `ModelState` is not valid you're passing the model to the `Add` view but if the `ModelState` is valid you're not passing anything so try ```return View("View", model);``` – Mohammed Alwedaei May 08 '23 at 12:00
  • If there is any error with other form values, it should display the same page with previous details like FirstName, etc.. and the attached file. – Balanjaneyulu K May 08 '23 at 14:25
  • Then why don't you create a ViewModel that contains the form values and the errors? i this way you can easily do what you want – Mohammed Alwedaei May 08 '23 at 14:28
  • You can't repopulate file upload fields. Have a look at [this](https://stackoverflow.com/questions/4205634/restoring-the-value-of-a-input-type-file-after-failed-validation). – Qing Guo May 09 '23 at 02:32

0 Answers0