ASP.NET CORE MVC Collect data and upload file

Robert Pettis 1 Reputation point
2022-08-04T13:13:28.153+00:00

I have a user for which I am collecting data and would like the user to upload a file that I would store on the server.
I have each piece of code written for collecting the data collected written to the database and stores the file name.
I also have it where the file uploads to the server.

Independently the Create and FileUpload code work however I am struggling to understand how I can combine the two.

I am not finding any examples of how to combine the two.
How could I call the FileUpload within the Create?

[HttpPost]  
        [ValidateAntiForgeryToken]  
        public async Task<IActionResult> Create([Bind("id,CompanyPN,Supplier,User,pdf_File,cad_File,")] Product product)  
        {  
            if (ModelState.IsValid)  
            {  
                _context.Add(product);  
                await _context.SaveChangesAsync();  
               
                return RedirectToAction(nameof(Index));  
            }  
            return View();  
        }  
  
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2022-08-05T06:49:06.913+00:00

    Hi @Robert Pettis ,

    You can refer to the following sample:

    1. Create two classes: Product and ProductViewModel class:
      228376-image.png
    2. Add the DbSet to the ApplicationDbContext and enable migration to generate the Product table.
      228395-image.png
    3. In the Controller Post method, based on the view model to create the Product instance and then insert it into the database.
      228320-image.png
    4. In the Create view page, remember to add the enctype attribute.
      228432-image.png

    You can view the source code from here: 228329-sourcecode.txt

    Then the output is like this:

    228423-1.gif

    Finally, here are some resources you can refer to them:

    ASP.NET Core MVC with EF Core - tutorial series

    Upload files in ASP.NET Core


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.