In this asp.net MVC post, we will learn how we create a complete custom simple registration form system with image upload using entity framework with jquery validation in MVC.

We will do registration functionality with the help of the entity framework, This Article is best for those who are beginning with asp.net MVC and like to learn the best way for user registration with image upload control.

So let’s start and create  an Mvc project , i have also create a folder for storing the uploaded image

ImageUploadFolder

Step 1

Let’s add entity framework for database operation ,follow the Step describe in the image

  • Right-Click on Model Folder=>Add=>New Item
  • Select data from left side menu and then select Ado entity framework

Create a Entity Framework

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>

The post Registration form with image upload in MVC using jquery Ajax appeared first on Software Development | Programming Tutorials.



Read More Articles