【发布时间】:2022-09-23 15:01:23
【问题描述】:
我在 ASP.NET Core 6 MVC 中练习 CRUD 操作。我尝试上传单张图片的方法。图像是在创建方法上上传的。但是当我尝试使用编辑方法而不改变图像时。它在 Edit post 方法上给出空值。
我将图像列作为字符串并仅保存由 AJAX url 通过 javascript 生成的随机名称。准时创建,图像上传+ javascript运行并获取随机名称+保存在数据库中。但是当我尝试编辑方法时,没有上传新图像,它保存为 Null(图像显示在编辑页面上。)
控制器Edit post 方法的代码:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, CustomerMaster customerMaster, IFormCollection formData)
{
if (ModelState.IsValid)
{
try
{
if (!_context.CustomerMasters.Any(x => x.MobileNo == customerMaster.MobileNo && x.CustomerId != id))
{
CustomerMaster customer = await _context.CustomerMasters.FindAsync(id);
customer.CustomerName = customerMaster.CustomerName;
customer.MobileNo = customerMaster.MobileNo;
customer.Email = customerMaster.Email;
customer.Address = customerMaster.Address;
customer.Image = customerMaster.Image;
customer.WhenEntered = DateTime.UtcNow;
_context.Update(customer);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
else
{
ModelState.AddModelError(\"\", \"Name with same mobile no. already exists.\");
}
}
return RedirectToAction(nameof(Index));
}
return View(customerMaster);
}
这是我的edit.cshtml:
\'\'\'\'
@model Customer_Crud_Demo.Models.CustomerMaster
@using Customer_Crud_Demo.Common
@{
ViewData[\"Title\"] = \"Edit\";
string imagePath = string.IsNullOrEmpty(Model.Image) ? \"https://via.placeholder.com/200x200\" : Config.customerImagePath + Model.Image.Replace(\".\", \".\");
}
在配置中
customerImagePath = \"/Content/MultiCustomerImg/\"
表单内的edit.cshtml
<form asp-action=\"Edit\" enctype=\"multipart/form-data\">
<div asp-validation-summary=\"ModelOnly\" class=\"text-danger\"></div>
<input type=\"hidden\" asp-for=\"CustomerId\" />
<label asp-for=\"Image\" class=\"control-label\"></label>
<table>
<tr>
<td>
<input type=\"file\" asp-for=\"Image\" id=\"fuCustomerImage\" class=\"fu form-control\" accept=\".jpg,.jpeg,.png\" />
</td>
<td>
<input type=\"button\" value=\"Upload\" id=\"btnUploadImage\" class=\"btn btn-primary\" data-URL=\"CustomerMaster/UploadFile\" data-path=\"/Content/CustomerImages\" />
</td>
</tr>
<tr>
<td>
<span asp-validation-for=\"Image\" class=\"text-danger\"></span>
</td>
</tr>
<tr>
<td class=\"error\" colspan=\"2\">
Please upload image of 200 X 200 and size less than 150KB.
</td>
</tr>
</table>
<div class=\"singleImage\">
<img src=\"@imagePath\" alt=\"Alternate Text\" id=\"ImgUploadedImage\" height=\"200\" width=\"200\" />
@Html.HiddenFor(model => model.Image, new { id = \"image\" })
</div>
</form>
我的错误是什么?请纠正我。
标签: c# asp.net-core .net-core file-upload image-upload