Reputation: 59
I want to make an e-commerce like web app using ASP.NET Core.
Creating the models is ok, but I need to make a way to upload images for the products.
Razor pages allow only one @model
, and this way I can't access the Image
class that I created for uploading the images. This Image
class is just a class for uploading, that will contain the path of the image, the id, the description and a NotMapped
IFormFile
property to do the upload.
But for UX purposes, the user(the owner of the e-commerce) to fill the Product
model and uploading the image in the same page, and do the POST
in the same form. But with the Razor pages allowing just one model, how can I do that? This way is dumb, impossible or both?
Thanks in advance.
Upvotes: 2
Views: 5865
Reputation: 53
can I use multi file like that;
ProductName:<input id="Text1" type="text" asp-for="product.Name" /><br />
choose file1:<input id="File1" type="file" asp-for="image.file" /><br />
choose file1:<input id="File2" type="file" asp-for="image.file" /><br />
choose file1:<input id="File3" type="file" asp-for="image.file" /><br />
choose file1:<input id="File4" type="file" asp-for="image.file" /><br />
Upvotes: 0
Reputation: 6881
But with the Razor pages allowing just one model, how can I do that? This way is dumb, impossible or both?
This is possible.
In razor page
, we usually bind different models by adding different type properties
, have a look for this.
According to your requirement, I created a demo for your reference:
Product model:
public class Product
{
public int Id { get; set; }
public string Name{ get; set; }
}
Image model:
public class Image
{
public string path { get; set; }
public int id{ get; set; }
public string description { get; set; }
[NotMapped]
public IFormFile file{ get; set; }
}
Page.cshtml.cs:
public class UploadTestModel : PageModel
{
[BindProperty]
public Image image { get; set; }
[BindProperty]
public Product product { get; set; }
public void OnGet()
{
}
public void OnPost()
{
}
}
Page.cshtml:
@page
@model WebApplication_razorpage.Pages.UploadTestModel
@{
ViewData["Title"] = "UploadTest";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
<h1>UploadTest</h1>
<form method="post" enctype="multipart/form-data">
ProductName:<input id="Text1" type="text" asp-for="product.Name" /><br />
choose file:<input id="File1" type="file" asp-for="image.file" /><br />
file description:<input id="Text1" type="text" asp-for="image.description" /><br />
<input id="Submit1" type="submit" value="submit" />
</form>
Here is the test result:
Upvotes: 5