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
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
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
- 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#
- Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
- Submit form with jquery ajax
- Passing array of strings to webmethod with variable number of arguments using jQuery AJAX
- How to ajax post an image to a C# web method with jquery
- How to Post file along with form data to MVC controller using Ajax?
- MVC with jQuery Ajax call does not correctly bind empty array/enumerable
- Ajax form serialize doesnt bind when using multiple parameters in MVC Controller
- upload file with other parameters through ajax in asp.net mvc
- Routing with Multiple Parameters using ASP.NET MVC
- How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?
- MVC razor form with multiple different submit buttons?
- ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
- ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"
- How to upload large files using MVC 4?
- MVC 4 Edit modal form using Bootstrap
- Post JSON with data AND file to Web Api - jQuery / MVC
- mvc upload file with model - second parameter posted file is null
- Using a PagedList with a ViewModel ASP.Net MVC
- Issue using ASP.Net MVC 4 Web API with Ninject.Web.WebApi
- Email address validation in C# MVC 4 application: with or without using Regex
- Create image with transparent background using GDI+?
- C# mvc 3 using selectlist with selected value in view
- Using Graphics.DrawImage() to Draw Image with Transparency/Alpha Channel
- How to resize and save an image which uploaded using file upload control in c#
- Message: Invalid JSON primitive: ajax jquery method with Webmethod
- Form with attachments upload and email sending
- How to download CSV file from ASP.NET Web Api using jQuery Ajax call
- Using Nininject MVC with class libraries
- Populate DropDownList using AJAX MVC 4
- sending mail along with embedded image using asp.net
- Calling BeginRead from a NetworkStream
- richtextbox advanced editing
- Replace a Date or Time section in a DateTime object in C#
- How To pass Optional Arguments
- How to Reference .xproj into .csproj?
- Could not load file or assembly 'BusinessObjects.Enterprise.Sdk.ZipLib.netmodule'
- Structuremap Scope/Lifecycle Guidance?
- Translating C# RSACryptoServiceProvider into JAVA Code
- Why does the C# compiler allow a duplicated variable in nested scope?
- Accessing to TempData From GLOBAL.ASAX
- Non-virtual interface design pattern in C#/C++
- Why is Stream.Copy faster than Stream.Write to FileStream?
- Speech Recognition on Kinect
- Center image on another image
- Difference between delegate.BeginInvoke and using ThreadPool threads in C#
- Combining multiple conditional expressions in C#
- Error dialog displayed when opening an excel file generated with EPPlus
- Taking ownership of files with 'broken' permissions
- how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7
- Take screenshot on test failure + exceptions