【发布时间】:2018-12-03 03:56:15
【问题描述】:
我使用 asp.net core razor pages 来创建我的应用程序,在我的创建页面中,我有两个文件控件,一个用于上传图标图像,另一个用于上传详细图像。但是当我点击编辑按钮时,所有的字段都被初始化了,除了两个文件控件。请检查我的代码。有人可以帮忙吗?
在我的剃须刀页面中:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Product.Icon" class="control-label"></label>
<input asp-for="@Model.Icon" type="file" />
<span asp-validation-for="Product.Icon" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label”>Detail Images(support multi-uploading):</label>
<input type="file" id="fUpload" name="files" multiple />
</div>
</div>
</div>
在我的页面模型中:
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
Product = await _context.Products
.Include(p => p.Shop).SingleOrDefaultAsync(m => m.ID == id);
if (Product == null)
{
return NotFound();
}
ViewData["Shop"] = new SelectList(_context.Shops, "ID", "Name");
return Page();
}
public async Task<IActionResult> OnPostAsync(List<IFormFile> files)
{
if (!ModelState.IsValid)
{
return Page();
}
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
if (!Directory.Exists(uploads))
{
Directory.CreateDirectory(uploads);
}
if (this.Icon != null)
{
var fileName = GetUniqueName(this.Icon.FileName);
var filePath = Path.Combine(uploads, fileName);
this.Icon.CopyTo(new FileStream(filePath, FileMode.Create));
this.Product.Icon = fileName;
}
if (files != null && files.Count > 0)
{
foreach (IFormFile item in files)
{
if (item.Length > 0)
{
var fn = GetUniqueName(item.FileName);
var fp = Path.Combine(uploads, fn);
item.CopyTo(new FileStream(fp, FileMode.Create));
this.Product.ProductImages = this.Product.ProductImages + fn + "^";
}
}
}
_context.Attach(Product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(Product.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
【问题讨论】:
-
文件控件无法初始化。在这里是为了从用户那里获取数据。如果您想向用户显示他们已经上传的文件/图像,只需显示这些文件/图像的链接列表。
-
@CodeNotFound 但如何编辑?您的意思是在编辑页面中,我应该显示上传的图像并将两个文件控件放在页面上,如果用户不上传新图像,则对图标和详细图像属性不做任何事情?
-
您无法编辑文件/图像。对于每个链接,只需放置一个删除按钮。用户删除文件/图像并使用文件控制添加另一个。
标签: c# razor asp.net-core razor-pages