.net 为什么在将多个模型转换为视图模型实体框架后,文件上载停止工作?

ws51t4hk  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(95)

控制器

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

查看模型

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

实体模型

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; }
}

检视

@model CollectionViewModel
         <form asp-action="Create" enctype="multipart/form-data" method="post" class="row g-3 mt-0">
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="col">
                    <label asp-for="staff.StaffFirstName" class="form-label"></label>
                    <input asp-for="staff.StaffFirstName" class="form-control" />
                    <span asp-validation-for="staff.StaffFirstName" class="text-danger"></span>
                </div>
                <div class="col">
                    <label asp-for="staff.StaffLastName" class="form-label"></label>
                    <input asp-for="staff.StaffLastName" class="form-control" />
                    <span asp-validation-for="staff.StaffLastName" class="text-danger"></span>
                </div>
                <div class="col-md-3">
                    <label asp-for="staff.StaffPhoto" class="form-label"></label>
                    <input asp-for="staff.StaffPhoto" type="file" accept="image/*" class="form-control" />
                    <span asp-validation-for="staff.StaffPhoto" class="text-danger"></span>
                    @{if (ViewBag.fileUploadErrorMessage != null)
                        {
                            <span class="text-danger">@ViewBag.fileUploadErrorMessage</span>
                        }
                    }
                </div>
           <div class="col">
                <input type="submit" value="Create" class="btn btn-primary" />
                <a asp-action="Create" class="btn btn-secondary">Reset All</a>
            </div>
        </form>
3ks5zfa0

3ks5zfa01#

您应该在模型中添加IFormFile

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

在视图中将StaffPhoto设置为asp-for。

<input asp-for="StaffPhoto" type="file" accept="image/*" class="form-control" />

相关问题