模型中的IFormFile始终为null

时间:2019-12-17 09:51:14

标签: .net-core asp.net-core-2.1 asp.net-core-2.2

我有一个要提交的文件上传表单,下面是ViewModel及其DataAnnotations。提交表单后,ModelState变为假。在ViewModel中检查File属性时,它为null。尽管我保留了enctype="multipart/form-data,但我仍然是null。

任何人都可以帮助我。

public class ExcelUploadViewModel
    {

        /// <summary>
        /// Gets or Sets the FileName
        /// </summary>
        [Required(ErrorMessage = "FileName is required")]
        public string FileName { get; set; }

        [Required(ErrorMessage = "File is required")]
        [DataType(DataType.Upload)]
        public IFormFile File { get; set; }
   }

Controller.cs

[HttpPost]
    public async Task<IActionResult> UploadExcel(ExcelUploadViewModel excelUploadModel)
    {
        if (ModelState.IsValid)
        {
            // HttpResponseMessage response;
            TransactionResultBase transactionResultBase = new TransactionResultBase();
            IFormFile file = Request.Form.Files[0];
        }
    }

和FormUpload.cshtml

<div align="left">
            <form id="uploadForm" enctype="multipart/form-data" name="uploadForm" asp-action="UploadExcel" method="post" >

                <div class="form-group form-group-lg form-group-sm row " >
                    <div class="col-sm-12 col-md-10 col-lg-10 uploadDiv" style="display: flex !important">
                        <label asp-for="FileName" class="col-sm-12 col-md-10 col-lg-10" style="font-size: 15px; max-width: fit-content ">File Name :</label>
                        <input asp-for="FileName" class="form form-control fileName"
                               type="text"
                               name="fileName"
                               placeholder="Enter your file name"
                               id="fileName" />
                        <span asp-validation-for="FileName" class="text-danger"></span>
                        <input asp-for="File" required class="form-control file" type="file" placeholder="File Name" id="file" name="uploadFile" />
                    </div>
                </div>
                <small>Please upload .xls or .xlxs or json or xml formatted files only</small>
                <div class="form-group form-group-lg form-group-sm row">
                    <div class="col-sm-12 col-md-10 col-lg-10">
                        <input type="submit" class="btn btn-primary" name="submit" id="fileUploadButton" value="Upload" />
                        <input type="reset" class="btn btn-Gray" name="result" id="resetButton" value="Reset" />
                    </div>
                </div>
            </form>
        </div>

1 个答案:

答案 0 :(得分:1)

标签助手根据模型生成ID和名称attiribute。因此,请勿同时使用标签助手和服装名字。

如果您要使用asp-for标签助手就足够了。如果要使用“名称”服装,则应根据您的型号和属性名称使用它。在这种情况下,由于您为文件输入name="uploadFile"使用了名称attiribute,因此您的模型无法确定该属性是哪个,因此您应该对其进行更正name="File"

如果在视图中使用viewmodel,请小心更改。