我用www.example.com的核心网络应用程序创建了一个文档上传网站asp.net,我遇到了一个小错误,但我不知道如何修复它。
在我的网站上,你首先创建一个“文件”,如下所示:
然后它会出现在列表中,如下所示:
当您按下upload attachment时,它会传递上一个表中的id,以确保它上传到正确的文件。
上传页面后面的代码如下,错误是如果在选择文件之前按upload,它会刷新页面显示错误,然后之前传递的ID已经丢失,所以myInv最终为null。
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>
上面是前端代码。
1条答案
按热度按时间7xllpg7q1#
您可以自定义错误消息
你还需要在视图中添加Jquery验证库:
然后,当用户不选择任何文件,并点击上传按钮,视图将显示错误消息,并停止上传的形式。