我用ASP.NET的核心Web应用程序创建了一个文档上传站点,我遇到了一个小错误,但我不确定如何修复它.

在我的网站上,你首先创建一个‘文件’,如下所示:

Create a file

然后,它会出现在如下所示的列表中:

file list

当您按下Upload Attach时,它会传递上一个表中的id,以确保上载到正确的文件.

upload attachment

上传页面背后的代码如下所示,错误是如果您在 Select 文件之前按Upload,它会刷新页面以显示错误,然后之前传递的ID丢失,因此myInv最终为空.

using FarmersPortal.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using File = FarmersPortal.Data.File;

namespace FarmersPortal.Pages.Admin
{
    [Authorize(Roles ="Admin")]
    public class UploadModel : PageModel
    {
        private readonly filedbContext _context;

        public UploadModel(filedbContext context)
        {

            _context = context;
        }
        public int? myID { get; set; }

        [BindProperty]
        public IFormFile file { get; set; }

        [BindProperty]
        public int? ID { get; set; }
        public void OnGet(int? id)
        {
            myID = id;
        }

        [BindProperty]
        public File File { get; set; }
        public async Task<IActionResult> OnPostAsync()
        {
            if (file != null)
            {
                if (file.Length > 0 && file.Length < 300000)
                {
                    var myInv = _context.Files.FirstOrDefault(x => x.Id == ID);
                    var date = DateTime.Today;

                    using (var target = new MemoryStream())
                    {
                        file.CopyTo(target);
                        myInv.UploadDate = date;
                        myInv.Attachment = target.ToArray();
                    }
                    if (myInv == null)
                    {
                        return NotFound();
                    }
                    else
                    {
                        File = myInv;
                    }
                    _context.Files.Update(myInv);
                    await _context.SaveChangesAsync();
                }

            }

            if (File.FileType == "Purchase Order")
            {
                return RedirectToPage("./PurchaseOrders");
            }
            else if (File.FileType == "Remittance")
            {
                return RedirectToPage("./Remittance");
            }
            else if (File.FileType == "Haulage Self Bill")
            {
                return RedirectToPage("./HaulageSelfBill");
            }
            else if (File.FileType == "Growers Return")
            {
                return RedirectToPage("./GrowersReturn");
            }
            return Page();
        }
    }
}

我不知道该怎么解决这个问题,你有什么主意吗?

@page
@model FarmersPortal.Pages.Admin.UploadModel
@{
}

<h1 style="color:white">Upload File</h1>

<style>
    body {
        background-image: url("http://10.48.1.215/PORTAL/hero-range-1.jpg");
        height: 100%;
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
    }
</style>

<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post" enctype="multipart/form-data">
            <div class="form-group">
                <div class="col-md-10">
                    <p style="color:white">Upload file</p>
                    <input type="hidden" asp-for="@Model.ID" value="@Model.myID" />
                    <input asp-for="file" class="form-control" accept=".pdf" type="file" />
                    <span asp-validation-for="file" class="text-white"></span>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-10">
                    <input class="btn btn-success" type="submit" value="Upload" />
                </div>
            </div>
        </form>
    </div>
</div>

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

上面是前端代码.

推荐答案

您可以自定义错误消息

[BindProperty]
[Required(ErrorMessage ="You must select a file before upload this form")]
public IFormFile file { get; set; }

您还需要将jQuery验证库添加到您的视图中:

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

然后,当用户没有 Select 任何文件并点击Upload按钮时,View将显示错误消息并停止上传表单.

enter image description here

Csharp相关问答推荐

Should. ThrowAsynock未捕获来自httpClient. GetAsynock()请求的异常

为什么使用DXGI输出复制和Direct 3D时捕获的图像数据全为零?

O(N)测试失败

如何循环遍历XML文档 node 以使用XSLT存储值

Elasticsearch:当我try 使用c#将嵌套对象添加到filter中时出现问题

C#DateTime.ToString在ubuntu和centos中返回不同的结果

AsNoTrackingWithIdentitySolutions()似乎不起作用?

更新产品但丢失产品ASP.NET Core的形象

将轮询与超时同步

MigraDoc文档

在EF Core中,有没有什么方法可以防止在查询中写入相同的条件,而代之以表达式?

为什么方法的值在SELECT方法中不会更改?

在字符串C#之前获取数字

按需无缝转码单个HLS数据段

在ASP.NET Core 8 MVC中本地化共享视图

单元测试类型为HttpClient with Microsoft.Extensions.Http.Resilience

WPF动态设置弹出窗口水平偏移

EF Core:如何对关系属性进行建模?

如何在使用属性 Select 器时判断是否可以为空

仅在Blazor Web App中覆盖生产的基本路径(.NET8中的_Hosts.cshtml文件功能?)