I am working on a social media application that requires a User Registration Controller to upload a user's profile image along with other user details. I aim to keep the File input field on the same Create/Edit view as the other fields such as Name, Display Name, Email Address, Phone Number, etc.

Essentially, I need a registration page where users can input various database fields, including an image file. This means posting the File Upload and other form fields to a single action in ASP.NET MVC.

I have successfully completed this task, and I believe sharing this idea with other developers could be helpful to them as well.

In this post, we will cover the following points

  1. File Upload input as Part of Form with Other Fields
  2. How to pass other form data field along with MVC File Upload?
  3. MVC 5 Uploading file with one additional parameter
  4. 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 illustrate with an example. I have created an MVC view containing input fields for Name, Display Name, Email Address, and Phone Number within a form. 

Additionally, the form includes a file upload control for uploading the user's profile picture. We have specified the standard form elements along with the file upload control using the 'multipart/form-data' enctype. This enctype allows handling of all form elements, including file uploads, 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.

  • It retrieves form data from the collection, including the user's full name, display name, email address, and phone number.It initializes a StudentDbEntities object to interact with the database.
  • It checks if a user with the same email address already exists in the database by querying the Users table.
  • If the user does not exist, it proceeds to create a new User object.It checks if the HTTP request contains a file (Request.Files.Count > 0) and if the file has content(Request.Files[0].ContentLength > 0).
  • If a file is present, it retrieves the file and saves it to the server's file system under the ~/Content/Images directory.
  • It sets the ProfilePicture property of the User object to the path of the saved image.It assigns values to the other properties of the User object (Name, DisplayName, Email, ContactNo).
  • It adds the User object to the Users table in the database and saves changes using db.SaveChanges().If the user is successfully registered, it sets a success message in the TempData and returns the "Index" view.
  • If the user already exists, it sets an error message in the ViewData and returns the "Index" view.If an exception occurs during the registration process, it catches the exception, sets the error message in the TempData, and returns the "Index" view.

Overall, this method provide an example, for the registration of a user's profile, including handling file uploads for the user's profile picture, and provides appropriate feedback messages based on the success or failure of the registration process.

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.