C
C#11mo ago
ShuajbM

how to upload a file in .net project

Im trying to fill a form with some attributes but when it comes to select a photo it doesnt work , who may cause the problem ?
108 Replies
ShuajbM
ShuajbMOP11mo ago
in fact , when i debug all fields are valid , only ImageUrl is Invalid
Angius
Angius11mo ago
ASP.NET Core I assume? Show your $code
MODiX
MODiX11mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Angius
Angius11mo ago
To send a file you would usually use IFormFile
ShuajbM
ShuajbMOP11mo ago
yes im actually using , only the imageurl attribute is invalid now ill send the code
c#
[HttpPost]
public IActionResult Upsert(PunetVM punetVM, IFormFile? file)
{
if (ModelState.IsValid)
{
if (file != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
punetVM.Punet.ImageUrl = @"\images\fotot\" + fileName;
}

if (punetVM.Punet.Id == 0)
{
// New record, add it
_unitOfWork.Punet.Add(punetVM.Punet);
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punetVM.Punet);
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
c#
[HttpPost]
public IActionResult Upsert(PunetVM punetVM, IFormFile? file)
{
if (ModelState.IsValid)
{
if (file != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
punetVM.Punet.ImageUrl = @"\images\fotot\" + fileName;
}

if (punetVM.Punet.Id == 0)
{
// New record, add it
_unitOfWork.Punet.Add(punetVM.Punet);
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punetVM.Punet);
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
this is the method in my controller and this is the form im trying to sumbit :
ShuajbM
ShuajbMOP11mo ago
ShuajbM
ShuajbMOP11mo ago
c#
public class PunetVM
{
public Punet Punet { get; set; }
}
c#
public class PunetVM
{
public Punet Punet { get; set; }
}
and the Punet model :
c# using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;

namespace Jobify.Models
{
public class Punet
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string Kerkesat { get; set; }
[Required]
public string Lokacioni { get; set; }

public string kategoria { get; set; }

public string ImageUrl { get; set; }
}
}
c# using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;

namespace Jobify.Models
{
public class Punet
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string Kerkesat { get; set; }
[Required]
public string Lokacioni { get; set; }

public string kategoria { get; set; }

public string ImageUrl { get; set; }
}
}
in my wwwroot folder i have a subfolder "image/fotot" , when i want to save the photos but this attribute isnt validating
c#
@model List<Punet>
<div class="container">
<div class="row pt-4 pb-3">
<div class="col-6">
<h2 class="text-primary">Punet List</h2>
</div>
<div class="col-6 text-end">
<a asp-controller="Punet" asp-action="Upsert" class="btn btn-primary">
Shto nje Pune <i class="bi bi-patch-plus"></i>
</a>
</div>
</div>

<table class="table table-bordered table-striped">
<thead>

<tr>
<th>Name</th>
<th>Description</th>
<th>Kerkesat</th>
<th>Lokacioni</th>
<th>Kategoria</th>
<th>ImageUrl</th>

</tr>
</thead>
<tbody>
@foreach(var obj in Model)
{
<tr>
<td>@obj.Name</td>
<td>@obj.Description</td>
<td>@obj.Kerkesat</td>
<td>@obj.Lokacioni</td>
<td>@obj.kategoria</td>
<td>@obj.ImageUrl</td>
<td>
<div class="w-75 btn-group" role="group">
<a asp-controller="Punet" asp-action="Upsert" asp-route-id="@obj.Id" class="btn btn-primary mx-2">
<i class="bi bi-pencil"></i> Edit
</a>
<a asp-controller="Punet" asp-action="Delete" asp-route-id="@obj.Id" class="btn btn-danger mx-2">
<i class="bi bi-trash3"></i> Delete
</a>
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
c#
@model List<Punet>
<div class="container">
<div class="row pt-4 pb-3">
<div class="col-6">
<h2 class="text-primary">Punet List</h2>
</div>
<div class="col-6 text-end">
<a asp-controller="Punet" asp-action="Upsert" class="btn btn-primary">
Shto nje Pune <i class="bi bi-patch-plus"></i>
</a>
</div>
</div>

<table class="table table-bordered table-striped">
<thead>

<tr>
<th>Name</th>
<th>Description</th>
<th>Kerkesat</th>
<th>Lokacioni</th>
<th>Kategoria</th>
<th>ImageUrl</th>

</tr>
</thead>
<tbody>
@foreach(var obj in Model)
{
<tr>
<td>@obj.Name</td>
<td>@obj.Description</td>
<td>@obj.Kerkesat</td>
<td>@obj.Lokacioni</td>
<td>@obj.kategoria</td>
<td>@obj.ImageUrl</td>
<td>
<div class="w-75 btn-group" role="group">
<a asp-controller="Punet" asp-action="Upsert" asp-route-id="@obj.Id" class="btn btn-primary mx-2">
<i class="bi bi-pencil"></i> Edit
</a>
<a asp-controller="Punet" asp-action="Delete" asp-route-id="@obj.Id" class="btn btn-danger mx-2">
<i class="bi bi-trash3"></i> Delete
</a>
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
when i Debug to if(ModelState.isValid) all fields are Valid only ImageUrl is Invalid ?!
Angius
Angius11mo ago
It's... not how I'd write most of the code, but aight. First and foremost, I'd use the viewmodel as actual viewmodel, not a useless wrapper around the database model That way you can have your IFomFile there and bind to it
ShuajbM
ShuajbMOP11mo ago
so which is the best way to store this and submit the form cuz im stuck i want to display the image too
Angius
Angius11mo ago
Does the file actually get saved? Does it appear where it should, and does the database entry look like it should?
ShuajbM
ShuajbMOP11mo ago
nah just the form repeats itself with all fields filled only imageurl isnt filled and says choose one file , so isnt submited
Angius
Angius11mo ago
So modelstate is not valid?
ShuajbM
ShuajbMOP11mo ago
and no photos are going to images/fotot no its not valid cuz of image when i Debug to if(ModelState.isValid) all fields are Valid only ImageUrl is Invalid ?!
Angius
Angius11mo ago
I guess I'd start by making the viewmodel an actual viewmodel, then
ShuajbM
ShuajbMOP11mo ago
so what to change to the code i think Upsert Method isnt functional
Angius
Angius11mo ago
[HttpPost]
public IActionResult Upsert(PunetVM punetVM)
[HttpPost]
public IActionResult Upsert(PunetVM punetVM)
public class PunetVM
{
public string Name { get; set; }
public string Description { get; set; }
public string Kerkesat { get; set; }
public string Lokacioni { get; set; }
public string Kategoria { get; set; }
public IFormFile File { get; set; }
}
public class PunetVM
{
public string Name { get; set; }
public string Description { get; set; }
public string Kerkesat { get; set; }
public string Lokacioni { get; set; }
public string Kategoria { get; set; }
public IFormFile File { get; set; }
}
The VM should contain everything you need, and only the things you need
ShuajbM
ShuajbMOP11mo ago
so you think this one to put in my ViewModel folder
Angius
Angius11mo ago
Then you can bind your file field to it
<div class="mb-3 p-1">
<label asp-for="File" class="p-0"></label>
<input asp-for="File" class="form-control" />
</div>
<div class="mb-3 p-1">
<label asp-for="File" class="p-0"></label>
<input asp-for="File" class="form-control" />
</div>
ShuajbM
ShuajbMOP11mo ago
but when i access to the PunetVM i have this attribute : public Punet Punet { get; set; }
Angius
Angius11mo ago
Well, don't As I said A viewmodel should be a viewmodel Not a wrapper for the database model
ShuajbM
ShuajbMOP11mo ago
okay but IFormFile how will it save in the database as a string ?
Angius
Angius11mo ago
Well, in your viewmodel, you will get the file You will then take it, save it somewhere on disk, like you're doing now Then you will get a path to it, on disk And save that in the database
ShuajbM
ShuajbMOP11mo ago
let me try it
Angius
Angius11mo ago
You will create a new Punet, and save that in the db The PunetVM will, at no point whatsoever, even touch the database
ShuajbM
ShuajbMOP11mo ago
so this code that i wrote wont work in anyway?
Angius
Angius11mo ago
The file saving code and the rest is fine It's just what you bind to is the issue That you're trying to use a wrapped up database model instead of an actual VM The rest looks fine
ShuajbM
ShuajbMOP11mo ago
so in this file that i have i should pass all the attributes that u send
Angius
Angius11mo ago
Yes Thew viewmodel should describe the data you want to send in or out It should be completely separate from the database models
ShuajbM
ShuajbMOP11mo ago
Id is required or not ?
Angius
Angius11mo ago
I would assume your database generates the IDs on insert, doesn't it?
ShuajbM
ShuajbMOP11mo ago
yes it does okay now there are error after i use the method u sent :
c#[HttpPost]
public IActionResult Upsert(PunetVM punetVM)
{
if (ModelState.IsValid)
{
if (file != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
punetVM.Punet.ImageUrl = @"\images\fotot\" + fileName;
}

if (punetVM.Punet.Id == 0)
{
// New record, add it
_unitOfWork.Punet.Add(punetVM.Punet);
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punetVM.Punet);
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
c#[HttpPost]
public IActionResult Upsert(PunetVM punetVM)
{
if (ModelState.IsValid)
{
if (file != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
punetVM.Punet.ImageUrl = @"\images\fotot\" + fileName;
}

if (punetVM.Punet.Id == 0)
{
// New record, add it
_unitOfWork.Punet.Add(punetVM.Punet);
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punetVM.Punet);
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
file doesnt exist in the current context
Angius
Angius11mo ago
Well, your punetVM no longer contains a Punet
ShuajbM
ShuajbMOP11mo ago
yes true
Angius
Angius11mo ago
It does contain the file, though So, no, there is not an individual file parameter There's a punetVM.File
ShuajbM
ShuajbMOP11mo ago
so instead
file
file
to use
punetVm.File
punetVm.File
Angius
Angius11mo ago
Yep
ShuajbM
ShuajbMOP11mo ago
this one : punetVM.Punet.ImageUrl = @"\images\fotot" + fileName; cuz it shows errors instead of Punet ?
Angius
Angius11mo ago
Ah, well, you have a viewmodel, but you don't have the database model now, right? You will have to create it, based on the viewmodel
ShuajbM
ShuajbMOP11mo ago
i did this : punetVM.File = @"\images\fotot" + fileName;
Angius
Angius11mo ago
For example,
var punet = new Punet {
Name = punetVM.Name,
ImageUrl = @"\images\fotot" + fileName,
// and so on
}
var punet = new Punet {
Name = punetVM.Name,
ImageUrl = @"\images\fotot" + fileName,
// and so on
}
punetVM is not your database model It will not, at any point, touch your database Punet is yor database model
ShuajbM
ShuajbMOP11mo ago
no only Punet is in my database
Angius
Angius11mo ago
Correct So you will need to create a new instance of Punet and fill it with data Some of that data you can take directly from the VM Some of it, you will have to create based on that. Like the image URL
ShuajbM
ShuajbMOP11mo ago
so what should i change to this method :
c# [HttpPost]
public IActionResult Upsert(PunetVM punetVM)
{
if (ModelState.IsValid)
{
if (punetVM.File != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(punetVM.File.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
punetVM.File.CopyTo(fileStream);
}
punetVM.File = @"\images\fotot\" + fileName;
}

if (punetVM.Punet.Id == 0)
{
// New record, add it
_unitOfWork.Punet.Add(punetVM.Punet);
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punetVM.Punet);
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
c# [HttpPost]
public IActionResult Upsert(PunetVM punetVM)
{
if (ModelState.IsValid)
{
if (punetVM.File != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(punetVM.File.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
punetVM.File.CopyTo(fileStream);
}
punetVM.File = @"\images\fotot\" + fileName;
}

if (punetVM.Punet.Id == 0)
{
// New record, add it
_unitOfWork.Punet.Add(punetVM.Punet);
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punetVM.Punet);
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
then i should change to Upsert.cshtml
Angius
Angius11mo ago
Ah, wait, it's an upsert In that case, I guess the viewmodel should have an ID as well And... I told you what to do Create a punet based on the vm For example like here Then you can _unitOfWork.Punet.Add(punet) Or _unitOfWork.Punet.Update(punet) But you need to create that punet first Based on the data from the VM And the data you create later, like a URL to the file
ShuajbM
ShuajbMOP11mo ago
can i share the screen cuz im new to this and dont understands those concepts so clearly if u have some time free
Angius
Angius11mo ago
c# [HttpPost]
public IActionResult Upsert(PunetVM punetVM)
{
if (ModelState.IsValid)
{
var punet = new Punet {
Id = punetVM.Id,
Name = punetVM.Name,
// ❗ all the other properties besides file URL
};

if (punetVM.File != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(punetVM.File.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
punetVM.File.CopyTo(fileStream);
}

// ❗ We instead set the file URL here
punet.ImageUrl = @"\images\fotot\" + fileName;
}

if (punetVM.Id == 0) // ❗ the VM no longer contains a Punet
{
// New record, add it
_unitOfWork.Punet.Add(punet); // ❗ The VM is separate from the database model, you need to add the actual database model you created
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punet); // ❗ Same here
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
c# [HttpPost]
public IActionResult Upsert(PunetVM punetVM)
{
if (ModelState.IsValid)
{
var punet = new Punet {
Id = punetVM.Id,
Name = punetVM.Name,
// ❗ all the other properties besides file URL
};

if (punetVM.File != null)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(punetVM.File.FileName);
string punetPath = Path.Combine(wwwRootPath, "images", "fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName), FileMode.Create))
{
punetVM.File.CopyTo(fileStream);
}

// ❗ We instead set the file URL here
punet.ImageUrl = @"\images\fotot\" + fileName;
}

if (punetVM.Id == 0) // ❗ the VM no longer contains a Punet
{
// New record, add it
_unitOfWork.Punet.Add(punet); // ❗ The VM is separate from the database model, you need to add the actual database model you created
}
else
{
// Existing record, update it
_unitOfWork.Punet.Update(punet); // ❗ Same here
}

_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}

// If ModelState is not valid, return to the view with errors
return View(punetVM);
}
ShuajbM
ShuajbMOP11mo ago
okay now im adding other attributes so i shouldnt include imageUrl attribute to the imageUrl
Angius
Angius11mo ago
? Also, just so we're clear, the [HttpPost] you have there is an example of an attribute What you mean is, I assume, a property $structure
MODiX
MODiX11mo ago
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;
}
}
namespace Namespace;

[Attribute]
public class Class
{
public string PublicField;
private bool _privateField;

public int PublicProperty { get; set; }

public Class() {} // Constructor

public void Method(int parameter)
{
var localVariable = parameter;
}
}
Angius
Angius11mo ago
Just so you're aware of the nomenclature
ShuajbM
ShuajbMOP11mo ago
c#
var punet = new Punet
{
Id = punetVM.Id,
Name = punetVM.Name,
Description=punetVM.Description,
Kerkesat=punetVM.Kerkesat,
Lokacioni=punetVM.Lokacioni,
kategoria=punetVM.Kategoria
// :exclamation: all the other properties besides file URL
};
c#
var punet = new Punet
{
Id = punetVM.Id,
Name = punetVM.Name,
Description=punetVM.Description,
Kerkesat=punetVM.Kerkesat,
Lokacioni=punetVM.Lokacioni,
kategoria=punetVM.Kategoria
// :exclamation: all the other properties besides file URL
};
Angius
Angius11mo ago
Correct At this point in time, you don't have the URL after all You have to save the file first, then get its location Only then can you set .ImageUrl property of your punet
ShuajbM
ShuajbMOP11mo ago
but i have some other errors in my Upsert Method which accepts a parameter int? id
c# public IActionResult Upsert(int? id)
{
//IEnumerable<SelectListItem> CategoryList = _unitOfWork.Category.
// GetAll().Select(u => new SelectListItem
// {
// Text = u.Name,
// Value = u.Id.ToString()
// });
//ViewBag.CategoryList = CategoryList;
//ViewData["CategoryList"] = CategoryList;
PunetVM punetVM = new()
{
Punet = new Punet()
};
if (id == null || id == 0)
{
//create ose insert

return View(punetVM);
}
else
{
//update
punetVM.Punet=_unitOfWork.Punet.Get(u=>u.Id == id);
return View(punetVM);
}

}
c# public IActionResult Upsert(int? id)
{
//IEnumerable<SelectListItem> CategoryList = _unitOfWork.Category.
// GetAll().Select(u => new SelectListItem
// {
// Text = u.Name,
// Value = u.Id.ToString()
// });
//ViewBag.CategoryList = CategoryList;
//ViewData["CategoryList"] = CategoryList;
PunetVM punetVM = new()
{
Punet = new Punet()
};
if (id == null || id == 0)
{
//create ose insert

return View(punetVM);
}
else
{
//update
punetVM.Punet=_unitOfWork.Punet.Get(u=>u.Id == id);
return View(punetVM);
}

}
ShuajbM
ShuajbMOP11mo ago
No description
Angius
Angius11mo ago
Well, yeah Your VM now looks different Again Again Again It no longer contains a Punet It has its own set of properties That you need to set So, in this case, you would do the inverse Instead of creating a punet based on the VM, you would create the VM based on your punet
public IActionResult Upsert(int? id)
{
//IEnumerable<SelectListItem> CategoryList = _unitOfWork.Category.
// GetAll().Select(u => new SelectListItem
// {
// Text = u.Name,
// Value = u.Id.ToString()
// });
//ViewBag.CategoryList = CategoryList;
//ViewData["CategoryList"] = CategoryList;

if (id == null || id == 0)
{
//create ose insert
var vm = new PunetVM(); // ❗ Create new VM
return View(punetVM);
}
else
{
//update
var punet = _unitOfWork.Punet.Get(u=>u.Id == id); // ❗ Get the punet
var vm = new PunetVM {
Name = punet.Name,
// ❗ Fill it with data
};
return View(vm);
}

}
public IActionResult Upsert(int? id)
{
//IEnumerable<SelectListItem> CategoryList = _unitOfWork.Category.
// GetAll().Select(u => new SelectListItem
// {
// Text = u.Name,
// Value = u.Id.ToString()
// });
//ViewBag.CategoryList = CategoryList;
//ViewData["CategoryList"] = CategoryList;

if (id == null || id == 0)
{
//create ose insert
var vm = new PunetVM(); // ❗ Create new VM
return View(punetVM);
}
else
{
//update
var punet = _unitOfWork.Punet.Get(u=>u.Id == id); // ❗ Get the punet
var vm = new PunetVM {
Name = punet.Name,
// ❗ Fill it with data
};
return View(vm);
}

}
ShuajbM
ShuajbMOP11mo ago
in this :
var vm = new PunetVM(); // :exclamation: Create new VM
return View(punetVM);
var vm = new PunetVM(); // :exclamation: Create new VM
return View(punetVM);
, should i make this one
:var vm = new PunetVM(); // :exclamation: Create new VM
return View(vm);
:var vm = new PunetVM(); // :exclamation: Create new VM
return View(vm);
Angius
Angius11mo ago
Yes, my bad
ShuajbM
ShuajbMOP11mo ago
and those :
var vm = new PunetVM
{
Name = punet.Name,
Description = punet.Description,
Kerkesat = punet.Kerkesat,
Lokacioni=punet.Lokacioni,
Kategoria=punet.kategoria,

// ❗ Fill it with data
};
var vm = new PunetVM
{
Name = punet.Name,
Description = punet.Description,
Kerkesat = punet.Kerkesat,
Lokacioni=punet.Lokacioni,
Kategoria=punet.kategoria,

// ❗ Fill it with data
};
is completed ? should i include the image ?
Angius
Angius11mo ago
Do you want to display the image? If so, then yes, you should add a property with the image's URL
ShuajbM
ShuajbMOP11mo ago
but
No description
ShuajbM
ShuajbMOP11mo ago
should i cast to smth how to convert this im trying like this: File = (IFormFile)punet.ImageUrl but it doesnt work 🥺 @jIMMACLE
Jimmacle
Jimmacle11mo ago
so where are you trying to display an image? and why do you think that means you need to cast a string to an IFormFile?
ShuajbM
ShuajbMOP11mo ago
cuz it wont compile cuz i need to cast or smth
Jimmacle
Jimmacle11mo ago
have you considered that that is a symptom of a more fundamental problem why would casting a string to an IFormFile work? a string is not an IFormFile
ShuajbM
ShuajbMOP11mo ago
i know
Jimmacle
Jimmacle11mo ago
so i'll ask for the 3rd time where are you trying to display the image?
ShuajbM
ShuajbMOP11mo ago
i have a Model called Punet , in this model i have some attributes and a file called ImageUrl as a string , then i have a ViewModel PunetVM and have the image as IFormFile , i want that image to display to Index.cshtml i mentioned above the conversation but i cant cast from string to IFormFile i have 2 methods Upsert in my Controller
Jimmacle
Jimmacle11mo ago
so how do you normally display an image in HTML?
ShuajbM
ShuajbMOP11mo ago
in ,img tag
Jimmacle
Jimmacle11mo ago
yes, and what do you put in the img tag to tell it to show a specific image?
ShuajbM
ShuajbMOP11mo ago
src
Jimmacle
Jimmacle11mo ago
and what does a src value look like?
ShuajbM
ShuajbMOP11mo ago
random url
Jimmacle
Jimmacle11mo ago
yes so you don't need an iformfile you just need a url
ShuajbM
ShuajbMOP11mo ago
look my code , i think its a bit complicated .
Jimmacle
Jimmacle11mo ago
it's not complicated if you want to display an image that your website is serving, you need to provide the URL of the image to the page which could be either a direct URL to a statically hosted image in wwwroot or a controller that can return the correct image based on something else
ShuajbM
ShuajbMOP11mo ago
all the fields are submited successfully only image isnt so when i debug
Jimmacle
Jimmacle11mo ago
well you aren't asking me about submitting anything you're asking me about displaying an image that's already on your site
ShuajbM
ShuajbMOP11mo ago
im trying to display that but i cant cuz the form isnt submited succesfully
Angius
Angius11mo ago
Submitting an image -> IFormFile Displaying an image -> URL of that image
Jimmacle
Jimmacle11mo ago
well that's an entirely different problem
Angius
Angius11mo ago
If you want a single viewmodel for both, it needs to contain both IFormFile File for submission string Url for display
ShuajbM
ShuajbMOP11mo ago
so what to write instead of : File=punet.ImageUrl cuz i cant cast
Angius
Angius11mo ago
You need another property
Jimmacle
Jimmacle11mo ago
you don't use IFormFile for the response
Angius
Angius11mo ago
A string property
Jimmacle
Jimmacle11mo ago
period
Angius
Angius11mo ago
Named Url or ImageUrl or something And put the URL of that image there When uploading the image:
YourViewModel {
+ IFormFile File = the actual file
- string ImageUrl = completely and entirely empty
// other properties
}
YourViewModel {
+ IFormFile File = the actual file
- string ImageUrl = completely and entirely empty
// other properties
}
When displaying the image, so going the other way:
YourViewModel {
- IFormFile File = completely and entirely empty
+ string ImageUrl = the URL to the file
// other properties
}
YourViewModel {
- IFormFile File = completely and entirely empty
+ string ImageUrl = the URL to the file
// other properties
}
Jimmacle
Jimmacle11mo ago
why is the request and response model shared anyway
ShuajbM
ShuajbMOP11mo ago
im not understanding , im a bit frustrated
Jimmacle
Jimmacle11mo ago
IFormFile is for submitting images from the frontend a plain string with a URL is all you need to send an image back
ShuajbM
ShuajbMOP11mo ago
in which place i need to change the code ? please
Angius
Angius11mo ago
data go browser to server -> you need iformfile data go server to browser -> you need string url
ShuajbM
ShuajbMOP11mo ago
im new as i mentioned
Jimmacle
Jimmacle11mo ago
the part where youre trying to cast your URL to an IFormFile for no reason
Angius
Angius11mo ago
Add a string property named ImageUrl to the viewmodel
ShuajbM
ShuajbMOP11mo ago
okay
Angius
Angius11mo ago
When sending data server to browser set that property to the file url Do NOT touch the IFormFile property then
ShuajbM
ShuajbMOP11mo ago
var vm = new PunetVM { Name = punet.Name, Description = punet.Description, Kerkesat = punet.Kerkesat, Lokacioni = punet.Lokacioni, Kategoria = punet.kategoria, ImageUrl=punet.ImageUrl
// ❗ Fill it with data }; now there is ok i think i added ImageUrl to ViewModel
Angius
Angius11mo ago
Yes
ShuajbM
ShuajbMOP11mo ago
now im gonna try this one errors went away in the upsert i removed "Punet.Name" only left "Name" when i click "Krijo " button , still it doesnt work ?
ShuajbM
ShuajbMOP11mo ago
No description
ShuajbM
ShuajbMOP11mo ago
it repeats all the fields
ShuajbM
ShuajbMOP11mo ago
Angius
Angius11mo ago
Make sure the optional properties of the VM are nullable, I guess? So Id, File, and ImageUrl? It probably complains because you don't send a new ImageUrl value And whether you send an ID is debatable That's why I don't like upsert forms
ShuajbM
ShuajbMOP11mo ago
so you think to make one for insert one for update
Angius
Angius11mo ago
That's how I'd do it, yes
ShuajbM
ShuajbMOP11mo ago
it takes time i think i have these methods
c#
public IActionResult Create()
{
return View();
}

[HttpPost]
public IActionResult Edit(Punet obj)
{
if (ModelState.IsValid)
{
_unitOfWork.Punet.Update(obj);
_unitOfWork.Save();
TempData["success"] = "Kateogria u perditesua me sukses";
return RedirectToAction("Index");
}
return View();
}
public IActionResult Edit(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
Punet? punetFromDb = _unitOfWork.Punet.Get(u => u.Id == id);
//Punet? punetFromDb2=_db.Categories.Where(u=>u.Id==id).FirstOrDefault();
if (punetFromDb == null)
{
return NotFound();
}
return View(punetFromDb);
}

[HttpPost]
public IActionResult Create(Punet obj,IFormFile? file)
{
if (ModelState.IsValid)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
if(file != null)
{
string fileName=Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string punetPath=Path.Combine(wwwRootPath, @"images\fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName),FileMode.Create))
{
file.CopyTo(fileStream);
}
obj.ImageUrl = @"\images\fotot\" + fileName;
Console.WriteLine($"ImageUrl: {obj.ImageUrl}");

}
_unitOfWork.Punet.Add(obj);
_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}
return View();
}
c#
public IActionResult Create()
{
return View();
}

[HttpPost]
public IActionResult Edit(Punet obj)
{
if (ModelState.IsValid)
{
_unitOfWork.Punet.Update(obj);
_unitOfWork.Save();
TempData["success"] = "Kateogria u perditesua me sukses";
return RedirectToAction("Index");
}
return View();
}
public IActionResult Edit(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
Punet? punetFromDb = _unitOfWork.Punet.Get(u => u.Id == id);
//Punet? punetFromDb2=_db.Categories.Where(u=>u.Id==id).FirstOrDefault();
if (punetFromDb == null)
{
return NotFound();
}
return View(punetFromDb);
}

[HttpPost]
public IActionResult Create(Punet obj,IFormFile? file)
{
if (ModelState.IsValid)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
if(file != null)
{
string fileName=Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string punetPath=Path.Combine(wwwRootPath, @"images\fotot");

using (var fileStream = new FileStream(Path.Combine(punetPath, fileName),FileMode.Create))
{
file.CopyTo(fileStream);
}
obj.ImageUrl = @"\images\fotot\" + fileName;
Console.WriteLine($"ImageUrl: {obj.ImageUrl}");

}
_unitOfWork.Punet.Add(obj);
_unitOfWork.Save();
TempData["success"] = "Puna u krijua me sukses";
return RedirectToAction("Index", "Punet");
}
return View();
}
but i need to modify them thank u anyway respect
Want results from more Discord servers?
Add your server