I am working on a social media application with a UseregistrationController that needs to upload a user profile image of each user in the application. I want to retain the File input on the same Create/Edit view as the other fields i.e Name, Display Name, Email Address, Phone Number, etc.
So basically I need a registration page where the user must enter several database fields, including an image file. i.e post File Upload and other form fields to one action in ASP.NET MVC.
I have completed my task successfully so I thought let’s share the idea with other developers also so that they can get help.
In this post, we will cover the following points
- File Upload input as Part of Form with Other Fields
- How to pass other form data field along with MVC File Upload?
- MVC 5 Uploading file with one additional parameter
- MVC File Upload with more than one property
In the below articles I have explained about Uploading both data and files in FormData using Ajax MVC. Now I think you are clear about uploading the image file with form data in ASP.Net MVC applications. if you want do this task using the ajax call then read below article.
Let’s understand with an example, I have created an MVC view that has Name, Display Name, Email Address, Phone Number input fields inside a form.
and that form control has one file upload control for uploading the user profile picture. and we have specified the standard form elements with a file upload “multipart/form-data“. So multipart type handle for all form elements on the page.
@using (Html.BeginForm("RegisterUserProfile", "UserDashboard", FormMethod.Post, new { @class = "log-form", area = "user", enctype = "multipart/form-data" })) { <div class="form-group row"> <label class="col-form-label col-md-2">Full Name * </label> <div class="col-md-10"> <input type="text" class="form-control" value="@ApplicationSession.UserSession.name" required name="fullname" id="fullname" placeholder="Enter Here"> </div> </div> <div class="form-group row"> <label class="col-form-label col-md-2">Display Name* </label> <div class="col-md-10"> <input type="text" class="form-control" value="@ApplicationSession.UserSession.displayname" required name="displayname" id="displayname" placeholder="Enter Here"> <p style="color: #9a9999;padding-top: 5px;">This will be how your name will be displayed in the account section.</p> </div> </div> <div class="form-group row"> <label class="col-form-label col-md-2">Email Address * </label> <div class="col-md-10"> <input type="email" required name="emailaddress" value="@ApplicationSession.UserSession.email" id="emailaddress" class="form-control" placeholder="Enter Here"> </div> </div> <div class="form-group row"> <label class="col-form-label col-md-2">Phone Number * </label> <div class="col-md-10"> <input type="tel" name="PhoneNumber" placeholder="Enter Here" value="@ApplicationSession.UserSession.phone" id="PhoneNumber" class="form-control" pattern="^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$" required> </div> </div> <div class="form-group row"> <label class="col-form-label col-md-2">Upload Photo * </label> <div class="col-md-10"> <input class="form-control" type="file" name="file" id="file"> </div> </div> <div class="text-left"> <button type="submit" class="btn btn-primary">Save Changes</button> </div> }
Action Method Code
In action using the FormCollection object I’m getting form data value inside the controller and In Request.Files we can read our files.Using the entity framework and I’m performing insert in a database table.
// Post:RegisterUserProfile [HttpPost] public ActionResult RegisterUserProfile(FormCollection collection) { //getting form data string fullname = collection["fullname"]; string displayname = collection["displayname"]; string emailaddress = collection["emailaddress"]; string phonenumber = collection["PhoneNumber"]; try { StudentDbEntities db1 = new StudentDbEntities(); var countuser = db1.Users.Where(a => a.Email == emailaddress.Trim()).Count(); if (countuser == 0) { using (StudentDbEntities db = new StudentDbEntities()) { User userobj = new User(); // Checking if Request object has file if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { HttpPostedFileBase file = Request.Files[0]; string fname = file.FileName; // Get the complete folder path and store the file inside it. fname = Path.Combine(Server.MapPath("~/Content/Images"), fname); file.SaveAs(fname); userobj.ProfilePicture = "/Content/Images/" + file.FileName; } userobj.Name = fullname; userobj.DisplayName = displayname; userobj.Email = emailaddress; userobj.ContactNo = phonenumber; db.Users.Add(userobj); db.SaveChanges(); TempData["ModelError"] = "registered successfully"; return View("Index"); } } else { ViewData["error"] = "email already exist please try with diffrent one!"; return View("Index"); } } catch (Exception ex) { TempData["ModelError"] = ex.Message; return View("Index"); } }
If you have any questions related to the post let me know, I will respond.
Please also share this article to Facebook, Twitter, Reddit, and other social media platform to help developers who face the same issue.
Please like our Facebook and follow us on Twitter for the latest update of technology or for any support.
MVC is a way in which we divide our database, logic, and visual part. The full form of MVC is Model-View-Controller, which means that we call the database the model, the logic part is known as the controller and the visual part is known as the view.
Talking about the technical language, it is such an architectural pattern, with the help of which project management, security, and productivity can be increased by dividing any project into 3 components.
We are not talking about anyone special programming language here because you can use it in any project, whether it is in PHP, ASP.NET, Nodejs, Python, you can use this method in all.
The post How to post File Upload and other form fields to one action Asp .Net MVC C# appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- How to restrict file upload to JPG, PNG, and GIF in ASP.NET MVC 3
- How to edit only few fields and disable other fields on my form on MVC?
- How to accept a file upload AND some data as a POST to a .NET REST API
- How to run two functions simultaneously without pausing each other in asp net mvc
- How to handle two route and direct to one Action in .NET-Core Mvc
- ASP NET Core MVC action returns bad request when trying to upload files with ajax
- How to create nlog loggers for various controllers and asp net mvc filters?
- How to create nlog loggers for various controllers and asp net mvc filters?
- MVC 5 How to upload Excel file and read rows till the last populated data row using EPPlus (OfficeOpenXml) ExcelPackage
- writing to xml file in one thread and in other thread restarting - how to do it safely?
- How to read text from file from one value to other in c#
- How to pass a JavaScript Array to ASP.Net MVC Action as part of post
- how can I extract number between two strings one is fixed and other is any thing
- How to copy a file from one folder to other in c#
- Is it possible to only specify one action (get/set) of an Automatic Property and have the other implemented?
- How could I build a dictionary in C# from a CSV file where the keys are in one column and the values in other?
- How to concatenate three fields as one and display in a datagridview table
- ASP.NET MVC Razor form to EF Create form with file upload
- How to allow only digits and one decimal point in a web form textbox
- How to read and parse specific integer value form a text file and add it to listbox in c#?
- How to properly implement DependencyService where one platform has synchronous code and other has asynchronous
- How can I return two values but only show one in a textbox and hide the other in C#
- C# Radio buttons: how can I assign two values to a single radio button. One text value for front-end user, and the other ID value for the program
- How do I retrieve only one specific file from a 7z instead of unzipping and dumping to a folder?
- How to access additional form data sent from jquery file upload in asp.net core?
- How do I redirect the user to a view once they've logged in and attempted to go back to the login screen ASP NET CORE
- How to download and upload file using SshClient .net
- How to return to another action within model and parameters in asp.net mvc 5?
- how to create two buttons within form and have only one submit form
- How to create Form On Top and cannot access other forms
- How to Bind Listbox in windows phone 8.1
- Custom dateTimepicker never updates value
- When Checkbox value is null. Program throws this error" Object cannot be cast from DBNull to other types."
- How can I listen to keyboard events in all controls of a Window?
- Parallel Task resulting wrong result
- How to do a loop to check all the variables at the same time for C#?
- mvc debugging with internet explorer
- WPF ComboBox not firing SelectionChanged event if placed at the bottom of Word AddIn
- Using Listview to Show Information Saved in the Database
- Web Form template vs Web API template
- Determine referenced type in static method
- How do i convert String to currency?
- Table border lines showing over panels ASP NET
- How to connect to webService on my PC from PPC - but this PC not connect to network?
- GetMessage() given an System.ExecutionEngineException
- C# WinForms - Error on OpenFileDialog MultiSelect: "Index was outside the bounds of the array."
- How to splice IP address into network address in C# / asp.net?
- Convert RGBA to just RGB but retain color in C#
- DocuSign -- Is the Quick Start code generator working for other developers?
- Excel row insert with C#