在ASP.NET Core 2剃须刀页面中上传文件 [英] File upload in ASP.NET Core 2 razor pages

查看:38
本文介绍了在ASP.NET Core 2剃须刀页面中上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在asp.net core 2剃须刀页面中做一个简单的文件上传.我有下面的代码.请意识到这是不完整的.当我在VS2017中运行时,我检查了FileUpload对象,不幸的是它为null.我希望它是null以外的东西,我可以创建一个流以从中获取一些数据.但是,由于该对象为null,因此我怀疑我没有正确地捆绑在一起的东西.任何想法表示赞赏.谢谢.

I'm trying to do a simple file upload in asp.net core 2 razor pages. I have the code below. Please realize that it is imcomplete. When i run in my VS2017, I check my FileUpload object, and it is unfortunately null. I would hope that it is something besides null and I could create a stream to get some data out of it. However, with the object being null, I would suspect that I do not have something tied together correctly. Any thoughts are appreciated. Thanks.

cs后面的代码:

public class PicturesModel : PageModel
{
    public PicturesModel()
    {

    }
    [Required]
    [Display(Name = "Picture")]
    [BindProperty]
    public IFormFile FileUpload { get; set; }

    public async Task OnGetAsync()
    {

    }

    public async Task<IActionResult> OnPostAsync()
    {
        //FileUpload is null
        return RedirectToPage("/Account/Pictures");
    }
}

前端cshtml文件;

front end cshtml file;

<form method="post" enctype="multipart/form-data">
    <label asp-for="FileUpload"></label>
    <input type="file" asp-for="FileUpload" id="file" name="file" />
    <input type="submit" value="Upload" />
</form>

推荐答案

您输入文件的属性名为 FileUpload ,但是您已覆盖了由TagHelper并将其重命名为与属性名称不匹配的 file .

Your property for the file input is named FileUpload but you have overridden the name attribute generated by the TagHelper and renamed it to file which does not match the property name.

将查看代码更改为

<input type="file" asp-for="FileUpload" />

,以便它生成正确的 name 属性(即 name ="FileUpload" ).另请注意,删除了 id ="file" ,这意味着您单击< label> 时不会将焦点设置到关联的控件上.

so that it generates the correct name attribute (which is name="FileUpload"). Note also the removal of id="file" which means that you <label> would not have set focus to the associated control when clicked).

这篇关于在ASP.NET Core 2剃须刀页面中上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆