In this ASP.NET MVC tutorial, we will learn how to create a custom registration form system with image upload functionality using Entity Framework and jQuery validation in MVC.
We will implement the registration functionality using Entity Framework. This tutorial is particularly beneficial for beginners in ASP.NET MVC who want to learn the proper way to implement user registration with an image upload control.
Let's begin by creating an MVC project. Additionally, we will create a folder to store the uploaded images."
Step 1
Let’s add entity framework for database operation ,follow the Step describe in the image
Step 2 –Create Controller
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UploadingFileMvc.Models;
namespace UploadingFileMvc.Controllers
{
public class AccountController : Controller
{
// GET: Account
public ActionResult Index()
{
DemoDBEntities db = new DemoDBEntities();
return View(db.TblCompanyUsers.ToList());
}
// Post:Register
[HttpPost]
public ActionResult UserRegistration()
{
try
{
//getting form data
string FullName = Request.Form["FullName"];
string Email = Request.Form["Email"];
string Password = Request.Form["Password"];
if(!IsEmailExist(Email))
{
if (Request.Files.Count > 0) // Checking if Request object has file
{
try
{
using (DemoDBEntities db = new DemoDBEntities())
{
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("~/Images/"), fname);
file.SaveAs(fname);
TblCompanyUser userobj = new TblCompanyUser
{
Email_Id = Email,
FullName = FullName,
ProfilePicture= "/Images/"+ file.FileName
};
db.TblCompanyUsers.Add(userobj);
if (db.SaveChanges() > 0)
{
//Set MVC and Login Authentication
return Json("User registered Successfully!");
}
else
{
return Json("Something went wrong please try again later!");
}
}
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
else
{
return Json("email already exist please try with diffrent one!");
}
}
catch (Exception e)
{
ModelState.AddModelError("", e.Message);
}
return View();
}
private bool IsEmailExist(string email)
{
bool IsEmailExist = false;
using (DemoDBEntities db = new DemoDBEntities())
{
int count = db.TblCompanyUsers.Where(a => a.Email_Id == email).Count();
if (count > 0)
{
IsEmailExist = true;
}
}
return IsEmailExist;
}
}
}
Let’s add view and Copy-paste below code
@model IEnumerable<UploadingFileMvc.Models.TblCompanyUser>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody class="tbody">
@foreach (var item in Model)
{
<tr>
<td class="PatientId">
<span>@item.UserId</span>
</td>
<td class="PatientName">
<img style="width: 50px;border-radius: 50%;" src="@item.ProfilePicture" />
<span>@item.FullName</span>
</td>
<td class="PatientNumber">
<span>@item.Email_Id</span>
</td>
</tr>
}
</tbody>
</table>
<form>
<fieldset>
<legend>Registration form with image upload in MVC using jquery Ajax</legend>
<div class="form-group">
<label for="txtName">Name</label>
<input type="text" class="form-control" id="txtName" placeholder="Name" />
</div>
<div class="form-group">
<label for="txtEmail">Email</label>
<input type="email" class="form-control" id="txtEmail" placeholder="Email" />
</div>
<div class="form-group">
<label for="txtpassword">Password</label>
<input type="password" class="form-control" id="txtpassword" placeholder="Password" />
</div>
<div class="form-group">
<label for="fileupload">Profile Picture</label>
<input type="file" class="form-control" id="fileupload" />
</div>
<div class="form-group">
<input type="button" id="btnregistered" value="Register" />
</div>
</fieldset>
</form>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$('#btnregistered').click(function () {
if (window.FormData !== undefined) {
var res = ValidateForm();
if (res == false) {
return false;
}
var fileUpload = $("#fileupload").get(0);
var files = fileUpload.files;
var fileData = new FormData();
fileData.append('FullName', $("#txtName").val());
fileData.append('Email', $("#txtEmail").val());
fileData.append('Password', $("#txtpassword").val());
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '/Account/UserRegistration',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
window.location.reload();
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("Your browser doesn support FormData");
}
});
function ValidateForm() {
var isValid = true;
if ($('#txtName').val().trim() == "") {
$('#txtName').css('border-color', 'Red');
isValid = false;
}
else {
$('#txtName').css('border-color', 'lightgrey');
}
if ($('#txtpassword').val().trim() == "") {
$('#txtpassword').css('border-color', 'Red');
isValid = false;
}
else {
$('#txtpassword').css('border-color', 'lightgrey');
}
if ($('#txtEmail').val().trim() == "") {
$('#txtEmail').css('border-color', 'Red');
isValid = false;
}
else {
$('#txtEmail').css('border-color', 'lightgrey');
}
return isValid;
}
});
</script>
Click Event Handler:
$('#btnregistered').click(function () { ... });: This binds a click event handler to the element with the ID "btnregistered". When this button is clicked, the function inside will execute.
Check for FormData Support:
if (window.FormData !== undefined) { ... }: This checks if the browser supports the FormData API, which is used to construct form data for AJAX requests.
Form Validation:
function ValidateForm() { ... }: This is a custom function for validating form fields. It checks if the name, email, and password fields are empty. If any field is empty, it sets the corresponding field's border color to red and returns false, indicating validation failure.
Construct FormData Object:
var fileData = new FormData();: Creates a new FormData object to store form data including file uploads.
Appending Form Data:
fileData.append('FullName', $("#txtName").val());: Appends the value of the name field (txtName) to the FormData object with the key "FullName".
fileData.append('Email', $("#txtEmail").val());: Appends the value of the email field (txtEmail) to the FormData object with the key "Email".
fileData.append('Password', $("#txtpassword").val());: Appends the value of the password field (txtpassword) to the FormData object with the key "Password".
Appending File Uploads:
for (var i = 0; i < files.length; i++) { ... }: Loops through all the files selected for upload and appends each file to the FormData object.
AJAX Request:
$.ajax({ ... });: Sends an AJAX request to the server.
Success and Error Handlers:
success: function (result) { ... }: Displays an alert with the result received from the server and reloads the page upon successful submission.
error: function (err) { ... }: Displays an alert with the error message if the request fails.