Home > front end >  Why File upload is stopped working after convert multiple models into a view model entity framework?
Why File upload is stopped working after convert multiple models into a view model entity framework?

Time:11-20

Controller

     public async Task<IActionResult> Create(IFormFile? StaffPhoto, CollectionViewModel collectionModel)
            {
            if (StaffPhoto != null){...} // issue is StaffPhoto value is null
            }

enter image description here

View Model

namespace Website.Models
{
    public class CollectionViewModel
    {
        public Staff staff { get; set; }
        public Contact contact { get; set; }
    }
}

Entity Model

public class Staff
    {
        public int StaffId { get; set; }

        [DisplayName("First Name")]
        [Required]
        public string StaffFirstName { get; set; }

        [DisplayName("Last Name")]
        [Required]
        public string StaffLastName { get; set; }

        [DisplayName("Photo")]
        public string? StaffPhoto { get; set; }
}

View

@model CollectionViewModel
         <form asp-action="Create" enctype="multipart/form-data" method="post" >
                <div asp-validation-summary="ModelOnly" ></div>
                <div >
                    <label asp-for="staff.StaffFirstName" ></label>
                    <input asp-for="staff.StaffFirstName"  />
                    <span asp-validation-for="staff.StaffFirstName" ></span>
                </div>
                <div >
                    <label asp-for="staff.StaffLastName" ></label>
                    <input asp-for="staff.StaffLastName"  />
                    <span asp-validation-for="staff.StaffLastName" ></span>
                </div>
                <div >
                    <label asp-for="staff.StaffPhoto" ></label>
                    <input asp-for="staff.StaffPhoto" type="file" accept="image/*"  />
                    <span asp-validation-for="staff.StaffPhoto" ></span>
                    @{if (ViewBag.fileUploadErrorMessage != null)
                        {
                            <span >@ViewBag.fileUploadErrorMessage</span>
                        }
                    }
                </div>
           <div >
                <input type="submit" value="Create"  />
                <a asp-action="Create" >Reset All</a>
            </div>
        </form>

CodePudding user response:

You should add IFormFile in model.

public class CollectionViewModel
{
    public Staff staff { get; set; }
    public IFormFile StaffPhoto { get; set; }
    public Contact contact { get; set; }
}

set StaffPhoto to asp-for in view.

<input asp-for="StaffPhoto" type="file" accept="image/*"  />
  • Related