I have a Edit form
and a file upload inside in, if upload file has file, everything is normal, but when it's empty it passes null
value to database. I use if
to check file upload length but it doesn't work. I also remove LogoFile
from Bind
.
here is my .cshtml code:
<form asp-action="Edit" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="FirstName" class="control-label"></label>
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LastName" class="control-label"></label>
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="LogoFile" class="control-label"></label><br />
<input asp-for="LogoFile" type="file" class="form-control" />
<img src="/@Html.DisplayFor(model => model.LogoFile)"/>
<span asp-validation-for="LogoFile" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="save" class="btn btn-green" />
</div>
</form>
and here is my controller code:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,FirstName,LastName")] Profile profile,IFormFile LogoFile)
{
if (id != profile.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
if (LogoFile != null || LogoFile.Length != 0)
{
var path = "images/" + LogoFile.FileName;
using (var stream = new FileStream("wwwroot/" + path, FileMode.Create))
{
await LogoFile.CopyToAsync(stream);
profile.LogoFile = path.ToString();
}
}
_context.Update(profile);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProfileExists(profile.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(profile);
}