Я хочу добавить новое изображение, а затем отобразить на странице в виде списка элементов. Итак, MemyController, где есть метод CreateMemy
memyContext db = new memyContext();
// GET: /<controller>/
public IActionResult Index()
{
var model = db.Memy.ToList();
return View(model);
}
public string Welcome(string name, string id)
{
return $"Hello, Your name's {name}. Your ID is {id}.";
}
public IActionResult CreateMeme()
{
return View();
}
[HttpPost]
public async Task<IActionResult> CreateMeme(Memy model, IFormFile fileUpload)
{
if (ModelState.IsValid)
{
string pathImgMovie = "/images/memy/";
string pathSave = $"wwwroot{pathImgMovie}";
if (!Directory.Exists(pathSave))
{
Directory.CreateDirectory(pathSave);
}
string extFile = Path.GetExtension(fileUpload.FileName);
string fileName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + extFile;
var path = Path.Combine(Directory.GetCurrentDirectory(), pathSave, fileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await fileUpload.CopyToAsync(stream);
}
DateTime dateNow = DateTime.Now;
model.coverImg = pathImgMovie + fileName;
model.releaseDate = dateNow;
model.modifyDate = dateNow;
db.Memy.Add(model);
await db.SaveChangesAsync();
return Redirect("{controller=Home}/{action=Index}/{id?}");
}
return View();
}
Я хочу сохранить изображение, которое добавлю в папку -/images/memy/
model memyContext
public partial class memyContext : DbContext
{
public memyContext(DbContextOptions<memyContext> options)
: base(options)
{
}
public memyContext() { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server = (localdb)\\mssqllocaldb; Database = memy");
}
public DbSet<Memy> Memy { get; set; }
}
и Views->Memy->CreateMeme
<h2>CreateMeme</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
@Html.LabelFor(model => model.Title, "Tytuł")
@Html.TextBoxFor(model => model.Title, new { @class = "form-control", placeholder = "podaj tytul" })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.releaseDate, "Data dodania")
<div class='input-group date' id='dtReleaseDate'>
@Html.TextBoxFor(model => model.releaseDate, new { @class = "form-control", placeholder = "relasedate" })
@Html.ValidationMessageFor(model => model.releaseDate, "", new { @class = "text-danger" })
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Category, "Gatunek")
@Html.DropDownListFor(m => m.Category, new List<SelectListItem>
{
new SelectListItem { Text="Śmieszne", Value="Śmieszne" },
new SelectListItem { Text="Poważne", Value="Poważne" },
new SelectListItem { Text="Głupie", Value="Głupie" }
}, "Podaj categorie mema", new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.Label("fileCoverImg", "Dodaj")
<input type="file" id="fileUpload" name="fileUpload" class="form-control" />
<lable class="text-danger">
@Html.ValidationMessage("errFileUpload")
</lable>
</div>
<div class=form-group>
<input onclick="return validateOnSubmit()" type="submit" value="CreateMeme" class="btn btn-primary" />
</div>
<div>
<a asp-controller="Home" asp-action="Index">Back to List</a>
</div>
}
@section Scripts
{
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript">
$(function () {
$('#dtReleaseDate').datetimepicker({
defaultDate: new Date(),
});
});
function validateOnSubmit() {
if (!$('#fileUpload').val()) {
$('span[data-valmsg-for="errFileUpload"]').text('The file upload is required.');
}
}
}
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
}
Когда я добавляю новый мем, папка images->memy
пуста, там должно быть изображение, которое я добавила.Похоже, у меня проблема с MemyController
и методом CreateMeme
, но я не могу найти никаких ошибок.Программа не показывает никаких ошибок.здесь
string pathImgMovie = "/images/memy/";
string pathSave = $"wwwroot{pathImgMovie}";
if (!Directory.Exists(pathSave))
{
Directory.CreateDirectory(pathSave);
}
Изображение должно быть сохранено в /images/memy/
, но этого не произошло, почему?Я сделал здесь точку останова if (ModelState.IsValid) {}
и понял, что программа не идет в этом if()
, есть ли проблемы с ModelState
?