EnumClass.cs
public enum EnumRole
{
SuperUser = 1,
Admin = 2,
Manager = 3
}
Step : 4 =>
DBConnection.cs :
public class DBConnection
{
private SqlConnection _sqlConnection;
private SqlCommand _sqlCommand;
public DBConnection()
{
_sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["UniversityDBConnection"].ConnectionString);
_sqlCommand = new SqlCommand();
}
public SqlConnection SqlConnectionObj
{
get
{
return _sqlConnection;
}
}
public SqlCommand SqlCommandObj
{
get
{
_sqlCommand.Connection = _sqlConnection;
return _sqlCommand;
}
}
}
Step 5 :
User.cs :
public class User
{
public int Id { get; set; } = 0;
public string Username { get; set; } = "";
public string Password { get; set; } = "";
public EnumRole Role { get; set; } = EnumRole.Manager;
public string Message { get; set; } = "";
public string RoleInString
{
get
{
return this.Role.ToString();
}
}
#region Methods
UserSignature userSignature = new UserSignature();
public User Save(User user)
{
return userSignature.Save(user);
}
public bool Delete(int id)
{
return userSignature.Delete(id);
}
public User Get(string username)
{
return userSignature.Get(username);
}
public User GetForLogin(string username, string password)
{
return userSignature.GetForLogin(username, password);
}
public List<User> Gets()
{
return userSignature.Gets();
}
public User Update(User user)
{
return userSignature.Update(user);
}
#endregion
#region internal signature
internal static IUserSignature Signature
{
get
{
UserSignature userSignature = new UserSignature();
return (IUserSignature)userSignature;
}
}
#endregion
}
#region interface
public interface IUserSignature
{
User Save(User user);
User Get(string username);
User GetForLogin(string username, string password);
List<User> Gets();
User Update(User user);
bool Delete(int id);
}
#endregion
Step 6 :
UserSignature.cs :
public class UserSignature : IUserSignature
{
UserDAL _userDAL = new UserDAL();
public UserSignature() { }
public bool Delete(int id)
{
return _userDAL.Delete(id);
}
public User Get(string username)
{
return _userDAL.Get(username);
}
public User GetForLogin(string username, string password)
{
return _userDAL.GetForLogin(username, password);
}
public List<User> Gets()
{
return _userDAL.Gets();
}
public User Save(User user)
{
_userDAL = new UserDAL();
return _userDAL.Save(user);
}
public User Update(User user)
{
return _userDAL.Update(user);
}
}
Step 7 :
UserDAL.cs :
public class UserDAL : DBConnection
{
public User Save(User user)
{
try
{
#region Insert
SqlConnectionObj.Open();
string sSQL = "INSERT INTO Users (Username, Password, Role) VALUES ('" + user.Username + "','" + user.Password + "','" + (int)user.Role + "')";
SqlCommandObj.CommandText = sSQL;
SqlCommandObj.ExecuteNonQuery();
SqlConnectionObj.Close();
#endregion
#region Get User
SqlConnectionObj.Open();
sSQL = "SELECT * FROM Users WHERE Id=(SELECT max(Id) FROM Users)";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
#endregion
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public List<User> Gets()
{
List<User> users = new List<User>();
User user = new User();
try
{
SqlConnectionObj.Open();
string sSQL = "SELECT * FROM Users";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
while (reader.Read())
{
user = new User();
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
users.Add(user);
}
SqlConnectionObj.Close();
return users;
}
catch (Exception ex)
{
users = new List<User>();
user = new User();
user.Message = ex.Message;
users.Add(user);
return users;
}
}
public User Get(string username)
{
User user = new User();
try
{
SqlConnectionObj.Open();
string sSQL = "SELECT * FROM Users WHERE Username = '" + username + "'";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
if (user.Id == 0)
{
user = new User();
user.Message = "No data found.";
}
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public User GetForLogin(string username, string password)
{
User user = new User();
try
{
SqlConnectionObj.Open();
string sSQL = "SELECT * FROM Users WHERE Username = '" + username + "' AND Password = '" + password + "'";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
if (user.Id == 0)
{
user = new User();
user.Message = "Invalid username or password";
}
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public User Update(User user)
{
try
{
#region Update User
SqlConnectionObj.Open();
string sSQL = "UPDATE Users SET Username = '" + user.Username + "', Password = '" + user.Password + "', Role = '" + (int)user.Role + "' WHERE Id = '" + user.Id + "'";
SqlCommandObj.CommandText = sSQL;
SqlCommandObj.ExecuteNonQuery();
SqlConnectionObj.Close();
#endregion
#region Get User
SqlConnectionObj.Open();
sSQL = "SELECT * FROM Users WHERE Id = '" + user.Id + "'";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
#endregion
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public bool Delete(int id)
{
try
{
SqlConnectionObj.Open();
string sSQL = "DELETE FROM Users WHERE Id = '" + id + "'";
SqlCommandObj.CommandText = sSQL;
SqlCommandObj.ExecuteNonQuery();
SqlConnectionObj.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
Step 8 :
UsersController.cs :
public class UsersController : Controller
{
User _user = new User();
public ActionResult Index()
{
List<User> users = new List<User>();
ViewBag.Roles = Enum.GetValues(typeof(EnumRole)).Cast<EnumRole>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }).ToList();
return View(users);
}
[HttpPost]
public JsonResult Save(User user)
{
try
{
_user = _user.Save(user);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Get(User user)
{
try
{
_user = _user.Get(user.Username);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Gets()
{
List<User> users = new List<User>();
try
{
users = _user.Gets();
}
catch (Exception ex)
{
users = new List<User>();
_user = new User();
_user.Message = ex.Message;
users.Add(_user);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(users);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Update(User user)
{
try
{
_user = _user.Update(user);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Delete(int id)
{
bool isSuccess = true;
try
{
isSuccess = _user.Delete(id);
}
catch (Exception ex)
{
isSuccess = false;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(isSuccess);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Login(User user)
{
try
{
_user = _user.GetForLogin(user.Username, user.Password);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
}
Step 9 :
Create User View (Index.cshtml) :
@{
Layout = null;
}
<html>
<head>
<title>CRUD Operation</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
<div style="float:left;width:50%;">
<table>
<tr>
<td colspan="2">
<input type="hidden" id="txtId" />
</td>
</tr>
<tr>
<td>Username</td>
<td>
<input type="text" id="txtUsername" placeholder="Type Username" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="txtPassword" placeholder="Type Password" />
</td>
</tr>
<tr>
<td>Role</td>
<td>
<select id="cboRole"></select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="btnGets" value="Get All" />
<input type="button" id="btnSave" value="Save" />
<input type="button" id="btnGet" value="Get" />
<input type="button" id="btnUpdate" value="Update" />
<input type="button" id="btnDelete" value="Delete" />
</td>
</tr>
<tr>
<td></td>
<td>
<label id="lblMessage"></label>
</td>
</tr>
</table>
<table id="tblDataTable">
<thead>
<tr>
<th>Username</th>
<th>Password</th>
<th>Role</th>
</tr>
<tr id="detailsTr">
</tr>
</thead>
</table>
</div>
<div style="float:right;width:50%;">
<table>
<tr>
<td>Username</td>
<td>
<input type="text" id="txtLoginUsername" placeholder="Type Username" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="txtLoginPassword" placeholder="Type Password" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="btnLogin" value="Login" />
</td>
</tr>
<tr>
<td></td>
<td>
<label id="lblLoginMessage"></label>
</td>
</tr>
</table>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
var roles = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.Roles));
var listItems = "";
for (var i = 0; i < roles.length; i++) {
listItems += "<option value='" + roles[i].Value + "'>" + roles[i].Text + "</option>";
}
$("#cboRole").html(listItems);
});
$("#btnSave").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame");
$("#txtUsername").focus();
return false;
}
if ($.trim($("#txtPassword").val()) == "") {
$("#lblMessage").text("Give Password");
$("#txtPassword").focus();
return false;
}
var user = {
Username: $("#txtUsername").val(),
Password: $("#txtPassword").val(),
Role: $("#cboRole").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Save",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if ($.trim(user.Message) == "") {
user.Message = "Succesfully Saved.";
Reset();
}
$("#lblMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnGet").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame");
$("#txtUsername").focus();
return false;
}
var user = {
Username: $("#txtUsername").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Get",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if ($.trim(user.Message) == "") {
$("#txtId").val(user.Id);
$("#txtUsername").val(user.Username);
$("#txtPassword").val(user.Password);
$("#cboRole").val(user.Role);
}
$("#lblMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnGets").click(function () {
$("#lblMessage").text("");
Reset();
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Gets",
traditional: true,
contentType: "application/json;charset=utf-8",
success: function (data) {
var users = jQuery.parseJSON(data);
if ($.trim(users[0].Message) == "") {
var result = "";
for (var i = 0; i < users.length; i++) {
$("#tblDataTable").append("<tr><td>" + users[i].Username + "</td><td>" + users[i].Password + "</td><td>" + users[i].RoleInString + "</td></tr>");
}
}
else {
$("#lblMessage").text(users[0].Message);
}
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnUpdate").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame and get user first");
$("#txtUsername").focus();
return false;
}
if ($.trim($("#txtPassword").val()) == "") {
$("#lblMessage").text("Give Password");
$("#txtPassword").focus();
return false;
}
var user = {
Id: $("#txtId").val(),
Username: $("#txtUsername").val(),
Password: $("#txtPassword").val(),
Role: $("#cboRole").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Update",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if ($.trim(user.Message) == "") {
user.Message = "Succesfully Updated.";
Reset();
}
$("#lblMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnDelete").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame and get user first");
$("#txtUsername").focus();
return false;
}
if(parseInt($("#txtId").val()) == ""){
$("#lblMessage").text("Give Usermame and get user first");
$("#txtUsername").focus();
return false;
}
if(!confirm("Confirm Delete ???"))
{
return false;
}
var message="";
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Delete?id=" + parseInt($("#txtId").val()),
traditional: true,
contentType: "application/json;charset=utf-8",
success: function (data) {
var result = jQuery.parseJSON(data);
if (result) {
message = "Succesfully Deleted.";
$("#txtId, #txtUsername, #txtPassword").val("");
} else {
message = "Error found.";
}
$("#lblMessage").text(message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
function Reset()
{
$("#txtId, #txtUsername, #txtPassword").val("");
$("#cboRole").val(1);
$("#tblDataTable td").remove();
}
$("#btnLogin").click(function () {
$("#lblLoginMessage").text("");
if ($.trim($("#txtLoginUsername").val()) == "") {
$("#lblLoginMessage").text("Give Usermame");
$("#txtLoginUsername").focus();
return false;
}
if ($.trim($("#txtLoginPassword").val()) == "") {
$("#lblLoginMessage").text("Give Password");
$("#txtLoginPassword").focus();
return false;
}
var user = {
Username: $("#txtLoginUsername").val(),
Password : $("#txtLoginPassword").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Login",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if($.trim(user.Message) == "")
{
if(user.Role == 1)
{
window.location.href = "/SuperuserDashboards/Index";
}
else if(user.Role == 2)
{
window.location.href = "/AdminDashboards/Index";
}
else if(user.Role == 3)
{
window.location.href = "/ManagerDashboards/Index";
}
else
{
window.location.href = "/Users/Index";
}
}
$("#lblLoginMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblLoginMessage").text(error);
}
});
});
</script>
Step 10 :
Change RouteConfig :
defaults: new { controller = "Users", action = "Index", id = UrlParameter.Optional }
OtherControllers :
public class AdminDashboardsController : Controller
{
public ActionResult Index()
{
return View();
}
}
https://www.dropbox.com/s/cro8wmfncbbxusx/CrudMVCwithLogin.rar?dl=0
public enum EnumRole
{
SuperUser = 1,
Admin = 2,
Manager = 3
}
Step : 4 =>
DBConnection.cs :
public class DBConnection
{
private SqlConnection _sqlConnection;
private SqlCommand _sqlCommand;
public DBConnection()
{
_sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["UniversityDBConnection"].ConnectionString);
_sqlCommand = new SqlCommand();
}
public SqlConnection SqlConnectionObj
{
get
{
return _sqlConnection;
}
}
public SqlCommand SqlCommandObj
{
get
{
_sqlCommand.Connection = _sqlConnection;
return _sqlCommand;
}
}
}
Step 5 :
User.cs :
public class User
{
public int Id { get; set; } = 0;
public string Username { get; set; } = "";
public string Password { get; set; } = "";
public EnumRole Role { get; set; } = EnumRole.Manager;
public string Message { get; set; } = "";
public string RoleInString
{
get
{
return this.Role.ToString();
}
}
#region Methods
UserSignature userSignature = new UserSignature();
public User Save(User user)
{
return userSignature.Save(user);
}
public bool Delete(int id)
{
return userSignature.Delete(id);
}
public User Get(string username)
{
return userSignature.Get(username);
}
public User GetForLogin(string username, string password)
{
return userSignature.GetForLogin(username, password);
}
public List<User> Gets()
{
return userSignature.Gets();
}
public User Update(User user)
{
return userSignature.Update(user);
}
#endregion
#region internal signature
internal static IUserSignature Signature
{
get
{
UserSignature userSignature = new UserSignature();
return (IUserSignature)userSignature;
}
}
#endregion
}
#region interface
public interface IUserSignature
{
User Save(User user);
User Get(string username);
User GetForLogin(string username, string password);
List<User> Gets();
User Update(User user);
bool Delete(int id);
}
#endregion
Step 6 :
UserSignature.cs :
public class UserSignature : IUserSignature
{
UserDAL _userDAL = new UserDAL();
public UserSignature() { }
public bool Delete(int id)
{
return _userDAL.Delete(id);
}
public User Get(string username)
{
return _userDAL.Get(username);
}
public User GetForLogin(string username, string password)
{
return _userDAL.GetForLogin(username, password);
}
public List<User> Gets()
{
return _userDAL.Gets();
}
public User Save(User user)
{
_userDAL = new UserDAL();
return _userDAL.Save(user);
}
public User Update(User user)
{
return _userDAL.Update(user);
}
}
Step 7 :
UserDAL.cs :
public class UserDAL : DBConnection
{
public User Save(User user)
{
try
{
#region Insert
SqlConnectionObj.Open();
string sSQL = "INSERT INTO Users (Username, Password, Role) VALUES ('" + user.Username + "','" + user.Password + "','" + (int)user.Role + "')";
SqlCommandObj.CommandText = sSQL;
SqlCommandObj.ExecuteNonQuery();
SqlConnectionObj.Close();
#endregion
#region Get User
SqlConnectionObj.Open();
sSQL = "SELECT * FROM Users WHERE Id=(SELECT max(Id) FROM Users)";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
#endregion
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public List<User> Gets()
{
List<User> users = new List<User>();
User user = new User();
try
{
SqlConnectionObj.Open();
string sSQL = "SELECT * FROM Users";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
while (reader.Read())
{
user = new User();
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
users.Add(user);
}
SqlConnectionObj.Close();
return users;
}
catch (Exception ex)
{
users = new List<User>();
user = new User();
user.Message = ex.Message;
users.Add(user);
return users;
}
}
public User Get(string username)
{
User user = new User();
try
{
SqlConnectionObj.Open();
string sSQL = "SELECT * FROM Users WHERE Username = '" + username + "'";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
if (user.Id == 0)
{
user = new User();
user.Message = "No data found.";
}
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public User GetForLogin(string username, string password)
{
User user = new User();
try
{
SqlConnectionObj.Open();
string sSQL = "SELECT * FROM Users WHERE Username = '" + username + "' AND Password = '" + password + "'";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
if (user.Id == 0)
{
user = new User();
user.Message = "Invalid username or password";
}
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public User Update(User user)
{
try
{
#region Update User
SqlConnectionObj.Open();
string sSQL = "UPDATE Users SET Username = '" + user.Username + "', Password = '" + user.Password + "', Role = '" + (int)user.Role + "' WHERE Id = '" + user.Id + "'";
SqlCommandObj.CommandText = sSQL;
SqlCommandObj.ExecuteNonQuery();
SqlConnectionObj.Close();
#endregion
#region Get User
SqlConnectionObj.Open();
sSQL = "SELECT * FROM Users WHERE Id = '" + user.Id + "'";
SqlCommandObj.CommandText = sSQL;
SqlDataReader reader = SqlCommandObj.ExecuteReader();
user = new User();
while (reader.Read())
{
user.Id = (int)reader["Id"];
user.Username = reader["Username"].ToString();
user.Password = reader["Password"].ToString();
user.Role = (EnumRole)Convert.ToInt32(reader["Role"].ToString());
}
SqlConnectionObj.Close();
#endregion
return user;
}
catch (Exception ex)
{
user = new User();
user.Message = ex.Message;
return user;
}
}
public bool Delete(int id)
{
try
{
SqlConnectionObj.Open();
string sSQL = "DELETE FROM Users WHERE Id = '" + id + "'";
SqlCommandObj.CommandText = sSQL;
SqlCommandObj.ExecuteNonQuery();
SqlConnectionObj.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
Step 8 :
UsersController.cs :
public class UsersController : Controller
{
User _user = new User();
public ActionResult Index()
{
List<User> users = new List<User>();
ViewBag.Roles = Enum.GetValues(typeof(EnumRole)).Cast<EnumRole>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }).ToList();
return View(users);
}
[HttpPost]
public JsonResult Save(User user)
{
try
{
_user = _user.Save(user);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Get(User user)
{
try
{
_user = _user.Get(user.Username);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Gets()
{
List<User> users = new List<User>();
try
{
users = _user.Gets();
}
catch (Exception ex)
{
users = new List<User>();
_user = new User();
_user.Message = ex.Message;
users.Add(_user);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(users);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Update(User user)
{
try
{
_user = _user.Update(user);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Delete(int id)
{
bool isSuccess = true;
try
{
isSuccess = _user.Delete(id);
}
catch (Exception ex)
{
isSuccess = false;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(isSuccess);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult Login(User user)
{
try
{
_user = _user.GetForLogin(user.Username, user.Password);
}
catch (Exception ex)
{
_user = new User();
_user.Message = ex.Message;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
string sJson = serializer.Serialize(_user);
return Json(sJson, JsonRequestBehavior.AllowGet);
}
}
Step 9 :
Create User View (Index.cshtml) :
@{
Layout = null;
}
<html>
<head>
<title>CRUD Operation</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
<div style="float:left;width:50%;">
<table>
<tr>
<td colspan="2">
<input type="hidden" id="txtId" />
</td>
</tr>
<tr>
<td>Username</td>
<td>
<input type="text" id="txtUsername" placeholder="Type Username" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="txtPassword" placeholder="Type Password" />
</td>
</tr>
<tr>
<td>Role</td>
<td>
<select id="cboRole"></select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="btnGets" value="Get All" />
<input type="button" id="btnSave" value="Save" />
<input type="button" id="btnGet" value="Get" />
<input type="button" id="btnUpdate" value="Update" />
<input type="button" id="btnDelete" value="Delete" />
</td>
</tr>
<tr>
<td></td>
<td>
<label id="lblMessage"></label>
</td>
</tr>
</table>
<table id="tblDataTable">
<thead>
<tr>
<th>Username</th>
<th>Password</th>
<th>Role</th>
</tr>
<tr id="detailsTr">
</tr>
</thead>
</table>
</div>
<div style="float:right;width:50%;">
<table>
<tr>
<td>Username</td>
<td>
<input type="text" id="txtLoginUsername" placeholder="Type Username" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="txtLoginPassword" placeholder="Type Password" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="button" id="btnLogin" value="Login" />
</td>
</tr>
<tr>
<td></td>
<td>
<label id="lblLoginMessage"></label>
</td>
</tr>
</table>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
var roles = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.Roles));
var listItems = "";
for (var i = 0; i < roles.length; i++) {
listItems += "<option value='" + roles[i].Value + "'>" + roles[i].Text + "</option>";
}
$("#cboRole").html(listItems);
});
$("#btnSave").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame");
$("#txtUsername").focus();
return false;
}
if ($.trim($("#txtPassword").val()) == "") {
$("#lblMessage").text("Give Password");
$("#txtPassword").focus();
return false;
}
var user = {
Username: $("#txtUsername").val(),
Password: $("#txtPassword").val(),
Role: $("#cboRole").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Save",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if ($.trim(user.Message) == "") {
user.Message = "Succesfully Saved.";
Reset();
}
$("#lblMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnGet").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame");
$("#txtUsername").focus();
return false;
}
var user = {
Username: $("#txtUsername").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Get",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if ($.trim(user.Message) == "") {
$("#txtId").val(user.Id);
$("#txtUsername").val(user.Username);
$("#txtPassword").val(user.Password);
$("#cboRole").val(user.Role);
}
$("#lblMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnGets").click(function () {
$("#lblMessage").text("");
Reset();
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Gets",
traditional: true,
contentType: "application/json;charset=utf-8",
success: function (data) {
var users = jQuery.parseJSON(data);
if ($.trim(users[0].Message) == "") {
var result = "";
for (var i = 0; i < users.length; i++) {
$("#tblDataTable").append("<tr><td>" + users[i].Username + "</td><td>" + users[i].Password + "</td><td>" + users[i].RoleInString + "</td></tr>");
}
}
else {
$("#lblMessage").text(users[0].Message);
}
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnUpdate").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame and get user first");
$("#txtUsername").focus();
return false;
}
if ($.trim($("#txtPassword").val()) == "") {
$("#lblMessage").text("Give Password");
$("#txtPassword").focus();
return false;
}
var user = {
Id: $("#txtId").val(),
Username: $("#txtUsername").val(),
Password: $("#txtPassword").val(),
Role: $("#cboRole").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Update",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if ($.trim(user.Message) == "") {
user.Message = "Succesfully Updated.";
Reset();
}
$("#lblMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
$("#btnDelete").click(function () {
$("#lblMessage").text("");
if ($.trim($("#txtUsername").val()) == "") {
$("#lblMessage").text("Give Usermame and get user first");
$("#txtUsername").focus();
return false;
}
if(parseInt($("#txtId").val()) == ""){
$("#lblMessage").text("Give Usermame and get user first");
$("#txtUsername").focus();
return false;
}
if(!confirm("Confirm Delete ???"))
{
return false;
}
var message="";
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Delete?id=" + parseInt($("#txtId").val()),
traditional: true,
contentType: "application/json;charset=utf-8",
success: function (data) {
var result = jQuery.parseJSON(data);
if (result) {
message = "Succesfully Deleted.";
$("#txtId, #txtUsername, #txtPassword").val("");
} else {
message = "Error found.";
}
$("#lblMessage").text(message);
},
error: function (xhr, status, error) {
$("#lblMessage").text(error);
}
});
});
function Reset()
{
$("#txtId, #txtUsername, #txtPassword").val("");
$("#cboRole").val(1);
$("#tblDataTable td").remove();
}
$("#btnLogin").click(function () {
$("#lblLoginMessage").text("");
if ($.trim($("#txtLoginUsername").val()) == "") {
$("#lblLoginMessage").text("Give Usermame");
$("#txtLoginUsername").focus();
return false;
}
if ($.trim($("#txtLoginPassword").val()) == "") {
$("#lblLoginMessage").text("Give Password");
$("#txtLoginPassword").focus();
return false;
}
var user = {
Username: $("#txtLoginUsername").val(),
Password : $("#txtLoginPassword").val()
};
$.ajax({
type: "POST",
dataType: "json",
url: "/Users/Login",
traditional: true,
data: JSON.stringify(user),
contentType: "application/json;charset=utf-8",
success: function (data) {
var user = jQuery.parseJSON(data);
if($.trim(user.Message) == "")
{
if(user.Role == 1)
{
window.location.href = "/SuperuserDashboards/Index";
}
else if(user.Role == 2)
{
window.location.href = "/AdminDashboards/Index";
}
else if(user.Role == 3)
{
window.location.href = "/ManagerDashboards/Index";
}
else
{
window.location.href = "/Users/Index";
}
}
$("#lblLoginMessage").text(user.Message);
},
error: function (xhr, status, error) {
$("#lblLoginMessage").text(error);
}
});
});
</script>
Step 10 :
Change RouteConfig :
defaults: new { controller = "Users", action = "Index", id = UrlParameter.Optional }
OtherControllers :
public class AdminDashboardsController : Controller
{
public ActionResult Index()
{
return View();
}
}
https://www.dropbox.com/s/cro8wmfncbbxusx/CrudMVCwithLogin.rar?dl=0