locked
If model is invalid then repoulate the files uploaded RRS feed

  • Question

  • User1185448985 posted

    On create action i'm allowing the user to upload a picture file, and based on the following view model if it is invalid during post action the message appear and the model is repopulated again with user's input except the file. i'm not sure if i can repopulate the file when the model is invalid

    ViewModel

    public class CreateEditChildViewModel
        {
            [Required]
            public string FirstName { get; set; }
    
            [Required]
            public string LastName { get; set; }
    
            [Required]
            public string DateOfBirth { get; set; }
    
            [Required]
            public string Gender { get; set; }
    
            [Required]
            public string EducationalLevel { get; set; }
    
            public string Picture { get; set; }
            public string Country { get; set; }
            public string Region { get; set; }
            public string City { get; set; }
        }

    Post Action

    [HttpPost]
            [ValidateAntiForgeryToken]
            public async Task<IActionResult> Create(CreateEditChildViewModel model)
            {
                if (ModelState.IsValid)
                {
                    string webRootPath = _hostingEnvironment.WebRootPath;
                    var files = HttpContext.Request.Form.Files;
    
                    var child = new Childs()
                    {
                        FirstName = model.FirstName,
                        LastName = model.LastName,
                        ParentOfId = model.ParentId,
                        SpecialistOfId = model.SpecialistId,
                        DateOfBirth = model.DateOfBirth,
                        Gender = model.Gender,
                        ...................
                    };
                    _db.Childs.Add(child);
                    await _db.SaveChangesAsync();
    
                    if (files.Count() > 0)
                    {
                        var uploads = Path.Combine(webRootPath, "images");
                        var extension = Path.GetExtension(files[0].FileName);
                        using (var filesStream = new FileStream(Path.Combine(uploads, child.Id + extension), FileMode.Create))
                        {
                            files[0].CopyTo(filesStream);
                        }
                        child.Picture = @"\images\" + child.Id + extension;
                    }
    
                    await _db.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
    
                CreateEditChildViewModel modelVM = new CreateEditChildViewModel()
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    ....................
                    //All model properties
                };
                return View(modelVM);
            }

    To sum up my question i would like to save the file input in case if the model is invalid i don't make the user to re-upload the file

    Saturday, October 17, 2020 11:26 PM

All replies

  • User-474980206 posted

    That is correct. If you don’t save the file on the server, the user must reselect and upload it. If you save it on the server, don’t ask for the file again. Browser security will not allow setting the file name or auto select.

    note: the only way to do what you want is to validate on client side.

    Sunday, October 18, 2020 4:35 PM
  • User1312693872 posted

    Hi, Amani AI

    i'm not sure if i can repopulate the file when the model is invalid

    You can try client validation, so if anything invalid, the model will not be passed to controller and your input will not be reset.

    You can check the tutorial about client validation.

    Following is a little demo:

    View:

    @{
        ViewData["Title"] = "Home Page";
        Layout = "_Layout";  //get < script src = "~/lib/jquery-validation/dist/jquery.validate.js" ></ script >
                             //    < script src = "~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" ></ script >
    } @model MyModel <form method="post" asp-action="..." asp-controller="..." enctype="multipart/form-data"> File: <input asp-for="myfile" /> <span asp-validation-for="myfile" class="text-danger"></span> <div> Id: <input asp-for="Id" /> <span asp-validation-for="Id" class="text-danger"></span> </div> <div> <button type="submit" class="btn btn-primary">Upload</button> </div> </form>

    Model:

     public class MyModel
        {
            [Required(ErrorMessage = "Please select a file.")]
            public IFormFile myfile { get; set; }
    
            [Required]
            [Range(0,5)]
            public int Id { get; set; }
        }

    Result:

    Best Regards,

    Jerry Cai

    Monday, October 19, 2020 9:18 AM