Uploading a file and submitting a form with razor Page.

swmikalson

New member
Joined
Feb 4, 2023
Messages
1
Programming Experience
1-3
I have been able to submit this form just fine to my database, but wanted to add the ability to upload a file at the same time and it sems I am having a disconnect with the examples I have seen as they focus on just the upload aspect.

As it stands I am unable to get ModelState.IsValid to be true even though it all worked before I added the file upload part.

Create.cshtml.cs:
using fed.Data;
using fed.Model;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace ferskened.Pages.fedAdmin.Repositories
{
    public class CreateModel : PageModel
    {
        private readonly ApplicationDbContext _context;
     
        public CreateModel(ApplicationDbContext context)
        {
            _context = context;
        }

        [BindProperty]
        public FileUpload fileUpload { get; set; }
        private string fullPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "UploadImages";

        public IActionResult OnGet()
        {
            ViewData["RepositoryTypeID"] = new SelectList(_context.RepositoryType, "RepoTypeId", "RepoName");
            ViewData["DocumentTypeID"] = new SelectList(_context.DocumentType, "DocumentTypeId", "DocumentName");
            return Page();
        }

        [BindProperty]
        public Repository Repository { get; set; } = default!;

        public async Task<IActionResult> OnPostAsync(FileUpload fileUpload)
        {
          if (!ModelState.IsValid || _context.Repository == null || Repository == null)
            {
                return Page();
            }

            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }
            var formFile = fileUpload.FormFile;
            if (formFile.Length > 0)
            {
                var filePath = Path.Combine(fullPath, formFile.FileName);

                using (var stream = System.IO.File.Create(filePath))
                {
                    formFile.CopyToAsync(stream);
                }
            }
         

            ViewData["SuccessMessage"] = formFile.FileName.ToString() + " files uploaded!!";
            _context.Repository.Add(Repository);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }

        public override bool Equals(object? obj)
        {
            return obj is CreateModel model &&
                   EqualityComparer<ApplicationDbContext>.Default.Equals(_context, model._context);
        }
    }
    public class FileUpload
    {
        [Required]
        [Display(Name = "File")]
        public IFormFile FormFile { get; set; }
        public string SuccessMessage { get; set; }
    }
}

The creat.cshtml file:
Create.cshtml:
@page
@model fed.Pages.fedAdmin.Repositories.CreateModel

@{
    ViewData["Title"] = "Create";
    Layout = "~/Pages/Shared/_Admin.cshtml";
}

<h1>Add Form or Template</h1>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Repository.RepositoryName" class="control-label"></label>
                <input asp-for="Repository.RepositoryName" class="form-control" />
                <span asp-validation-for="Repository.RepositoryName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Repository.RepositoryDescription" class="control-label"></label>
                <input asp-for="Repository.RepositoryDescription" class="form-control" />
                <span asp-validation-for="Repository.RepositoryDescription" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Repository.RepositoryLink" class="control-label"></label>
                <input asp-for="Repository.RepositoryLink" class="form-control" />
                <span asp-validation-for="Repository.RepositoryLink" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Repository.RepositoryImage" class="control-label"></label>
                <input asp-for="Repository.RepositoryImage" class="form-control" />
                <span asp-validation-for="Repository.RepositoryImage" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Repository.RepositoryTypeId" class="control-label"></label>
                <select asp-for="Repository.RepositoryTypeId" class="form-control" asp-items="ViewBag.RepositoryTypeId"></select>
            </div>
            <div class="form-group">
                <label asp-for="Repository.DocumentTypeId" class="control-label"></label>
                <select asp-for="Repository.DocumentTypeId" class="form-control" asp-items="ViewBag.DocumentTypeId"></select>
            </div>
            <div class="form-group">
                <label class="file">
                    <input type="file" asp-for="fileUpload.FormFile" aria-label="File browser example">
                    <span class="file-custom"></span>
                </label>
                <input asp-page-handler="Upload" class="btn btn-primary" type="submit" value="Upload">
            </div>
            <br /><br />
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}



and finally the model:
C#:
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using fed.Model.Types;

namespace fed.Model
{
    public class Repository
    {
        [Key]
        public int RepositoryId { get; set; }

        [Required]

        [DisplayName("Title")]
        public string RepositoryName { get; set; }

        [Required]

        [DisplayName("Description")]
        public string? RepositoryDescription { get; set; }

        [DisplayName("Link")]
        public string? RepositoryLink { get; set; }

        [DisplayName("Display Image")]
        public string? RepositoryImage { get; set; }

        [ForeignKey("Repository Type")]
        public int RepositoryTypeId { get; set; }
        public RepositoryType? RepositoryType { get; set; }

        [ForeignKey("Document Type")]
        public int DocumentTypeId { get; set; }
        public DocumentType? DocumentType { get; set; }

    }
}
 
Last edited by a moderator:
What happens if you comment out the declaration for SuccessMessage on line 73?
 
Back
Top Bottom