上传文件并解压缩FileName后,我无法在更新数据库之前将值分配给我的模型。文件正确上传,表单中的其他数据更新,不会发生错误。
表格:
<form method="post" enctype="multipart/form-data">
<input asp-for="Product.Name" />
<input type="file" name="ImageFile" />
@for(var i = 0; i < 10; i++) {
<input asp-for="Product.ProductIntervals[i].Name" />
[...]
}
</form>
OnPostAsync:
public async Task<IActionResult> OnPostAsync(CreateEditProduct model, IFormFile imageFile)
{
if (!ModelState.IsValid) return Page();
if (imageFile != null)
{
var fileName = imageFile.FileName;
var uploadPath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
imageFile.CopyTo(new FileStream(uploadPath, FileMode.Create));
model.Product.Image = fileName;
}
if (await TryUpdateModelAsync(
model.Product,
"Product",
x => x.Name,
//x => x.Image
))
{
_dbContext.Update(model.Product);
foreach (var x in model.Product.ProductIntervals)
{
bool newInterval = x.Id == Guid.Empty;
var interval = new ProductInterval
{
Id = newInterval ? Guid.NewGuid() : x.Id,
Name = x.Name,
IntervalMonths = x.IntervalMonths,
IntervalDays = x.IntervalDays,
Priority = x.Priority,
ProductId = model.Product.Id,
Status = x.Status
};
if (newInterval)
{
await _dbContext.AddAsync(interval);
}
else
{
_dbContext.Update(interval);
}
}
await _dbContext.SaveChangesAsync();
return RedirectToPage("./index");
}
return Page();
}
该模型:
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public IList<ProductInterval> ProductIntervals { get; set; }
}
public class CreateEditProduct {
public Product Product { get; set; }
public IList<ProductCategory> ProductCategories { get; set; }
}
我在TryUpdateModelAsync中尝试使用/不使用x => x.Image,没有区别。
怎么了?
我认为你错过了你的模型和DbContext
之间的联系 - 除非你在你简化的代码部分的某处指定它。
例如添加_dbContext.Update()
调用你的控制器方法解决问题?
public async Task<IActionResult> OnPostAsync(CreateEditProduct model, IFormFile imageFile, string existingImage)
{
if (!ModelState.IsValid) return Page();
if (imageFile != null)
{
var fileName = imageFile.FileName;
[...]
model.Product.Image = fileName;
}
if (await TryUpdateModelAsync(
model.Product,
"Product",
x => x.Image,
[...]
)){
_dbContext.Update(model); // or model.Product if you only need to save changes to Product
await _dbContext.SaveChangesAsync();
}
或者,您可以在验证检查后立即调用_dbContext.attach(model);
,让实体框架跟踪您的模型的相关更改。