Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have deigned a MVC-6 Application with two forms ,one is Registration form and after Registration I have another form to Login with the same UserName and Password which was entered during registration.What ever I have mention for error message display while register with same data,so the error message is not displaying.....

I am expecting if User is already exist in my database the error message should be display as "user is already exist..."
Please help me out with regarding solution...

Thanks in Advance,

What I have tried:

C#
---Here Is My LogInController----
 public class LoginController : Controller
    {
        //GET mothod
        public ActionResult Login()
        {
            return View();
        }
        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult LogIn(string userName, string password)
        {
            try
            {
                using (var context = new CmsDbContext())
                {
                    var getUser = (from s in context.ObjRegisterUser where s.UserName == userName || s.EmailId == userName select s).FirstOrDefault();
                    if (getUser != null)
                    {
                        var hashCode = getUser.VCode;
                        //Password Hasing Process Call Helper Class Method    
                        var encodingPasswordString = Helper.EncodePassword(password, hashCode);
                        //Check Login Detail User Name Or Password    
                        var query = (from s in context.ObjRegisterUser where (s.UserName == userName || s.EmailId == userName) && s.Password.Equals(encodingPasswordString) select s).FirstOrDefault();
                        if (query != null)
                        {
                            //RedirectToAction("Details/" + id.ToString(), "FullTimeEmployees");    
                            //return View("../Admin/Registration"); url not change in browser    
                            return RedirectToAction("Index", "Admin");
                        }//I want to display this below error but not displaying
                        
                            ViewBag.ErrorMessage = "Invallid User Name or Password";
                            return View();
                        }
                        ViewBag.ErrorMessage = "Invallid User Name or Password";//
                        return View();
                    }
            }
            catch (Exception)
            {
                ViewBag.ErrorMessage = " Error!!! contact abc@info.in";
                return View();
            }

-----here is my Login view---
XML
@{
    ViewBag.Title = "LogIn";
}

<h2>LogIn</h2>

<div class="form-horizontal">
    @using (Html.BeginForm("LogIn", "Login", null, FormMethod.Post))
    { @Html.AntiForgeryToken()
       
        <div class="form-group">
            <div class="col-md-12">
                <input type="text" class="form-control" required="" placeholder="E-mail" name="UserName" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-12">
                <input type="password" class="form-control" required="" placeholder="Password" name="Password" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-2">
                <button class="btn btn-info btn-block">Log In</button>
            </div>
            </div>
            <div class="form-group">
                <div class="col-md-2"> <a href="#" class="btn btn-link btn-block">Forgot your password?</a> </div>

            </div>
            <div class="login-subtitle"> Don't have an account yet?</div>
            <div>
    @Html.ActionLink("Create an account", "Registration", "Admin") </div> }
            </div>

-------here is my user model class---
C#
public class User
    {
            [Key]
            public int RegistrationId { get; set; }

            //This will be primary key column with auto increment  
            public string FirstName { get; set; }
    
            public string LastName { get; set; }

        
        public string UserName { get; set; }
       

        public string EmailId { get; set; }

            public string Password { get; set; }

            public string Gender { get; set; }
        
            public string VCode { get; set; }
            public DateTime CreateDate { get; set; }

            public DateTime ModifyDate { get; set; }

            public bool Status { get; set; }

--here is my Registration Controller---
C#
// GET: Admin
       public ActionResult Index()
       {
           return View();
       }

       // GET: Admin/Details/5

       public ActionResult Registration()
       {
           return View();
       }
       [ValidateAntiForgeryToken]
       [HttpPost]
       public ActionResult Registration(User objNewUser)
       {
           try
           {
               using (var context = new CmsDbContext())
               {
                   var chkUser = (from s in context.ObjRegisterUser where s.UserName == objNewUser.UserName || s.EmailId == objNewUser.EmailId select s).FirstOrDefault();
                   if (chkUser == null)
                   {
                       var keyNew = Helper.GeneratePassword(10);
                       var password = Helper.EncodePassword(objNewUser.Password, keyNew);
                       objNewUser.Password = password;
                       objNewUser.CreateDate = DateTime.Now;
                       objNewUser.ModifyDate = DateTime.Now;
                       objNewUser.VCode = keyNew;
                       context.ObjRegisterUser.Add(objNewUser);
                       context.SaveChanges();
                       ModelState.Clear();
                       return RedirectToAction("LogIn", "Login");
                   }

                   ViewBag.ErrorMessage = "User Allredy Exixts!!!!!!!!!!";//---not displaying this error message//
                   return View();
               }
           }
           catch (Exception e)
           {
               ViewBag.ErrorMessage = "Some exception occured" + e;
               return View();
           }
       }

--here is my registration view---
XML
<h2>Registration</h2>

<div class="panel panel-default mb0">
    <div class="panel-heading ui-draggable-handle">
        <h3 class="panel-title">New User   Registration</h3>
    </div> @using (Html.BeginForm("Registration", "Admin", null, FormMethod.Post))
    { @Html.AntiForgeryToken()
      
        <div class="panel-body">
            <div class="form-group pt20">
                <label class="col-md-3 col-xs-12 control-label align-right pt7">First Name</label>
                <div class="col-md-6 col-xs-12">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="fa fa-pencil"></span></span>
                        <input type="text" class="form-control form-group" required="" name="FirstName"> @*Getting value by name and the name should be the name given in database column*@
                    </div> <span class="help-block">First Name field sample</span>
                </div>
                <div class="clearfix"></div>
            </div>
            <div class="form-group">
                <label class="col-md-3 col-xs-12 control-label align-right pt7">Last Name</label>
                <div class="col-md-6 col-xs-12">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="fa fa-pencil"></span></span>
                        <input type="text" class="form-control form-group" required="" name="LastName"> @*Getting value by name and the name should be the name given in database column*@
                    </div> <span class="help-block">Last Name field sample</span>
                </div>
                <div class="clearfix"></div>
            </div>
            <div class="form-group">
                <label class="col-md-3 col-xs-12 control-label align-right pt7">User Name</label>
                <div class="col-md-6 col-xs-12">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="fa fa-pencil"></span></span>
                        <input type="text" class="form-control form-group" required="" name="UserName"> @*Getting value by name and the name should be the name given in database column*@
                    </div> <span class="help-block">User Name field sample</span>
                </div>
                <div class="clearfix"></div>
            </div>
            <div class="form-group">
                <label class="col-md-3 col-xs-12 control-label align-right pt7">Email Id</label>
                <div class="col-md-6 col-xs-12">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="fa fa-pencil"></span></span>
                        <input type="text" class="form-control form-group" required="" name="EmailId"> @*Getting value by name and the name should be the name given in database column*@
                    </div> <span class="help-block">Email-Id field sample</span>
                </div>
                <div class="clearfix"></div>
            </div>
            <div class="form-group">
                <label class="col-md-3 col-xs-12 control-label align-right pt7">Password</label>
                <div class="col-md-6 col-xs-12">
                    <div class="input-group">
                        <span class="input-group-addon"><span class="fa fa-unlock-alt"></span></span>
                        <input type="password" class="form-control" required="" name="Password">
                    </div> <span class="help-block">Password field sample</span>
                </div>
                <div class="clearfix"></div>
            </div>
            <div class="form-group">
                <label class="col-md-3 col-xs-12 control-label align-right pt7">Gender</label>
                <div class="col-md-6 col-xs-12">
                    <label class="radio-inline">
                        <input type="radio" checked="checked" value="Male" name="Gender">Male
                    </label>
                    <label class="radio-inline">
                        <input type="radio" value="Female" name="Gender">Female
                    </label>
                </div>
                <div class="clearfix"></div>
            </div>
        </div>
        <div class="panel-footer">
            <input type="reset" value="Clear Form" name="btnReset" class="btn btn-default" />
            <input type="submit" id="btnSubmit" name="btnSubmit" value="Submit" class="btn btn-primary pull-right" />
        </div> }
</div>  

---here is my another helper class for password hash---
C#
public static class Helper
    {
        public static string ToAbsoluteUrl(this string relativeUrl) //Use absolute URL instead of adding phycal path for CSS, JS and Images     
        {
            if (string.IsNullOrEmpty(relativeUrl)) return relativeUrl;
            if (HttpContext.Current == null) return relativeUrl;
            if (relativeUrl.StartsWith("/")) relativeUrl = relativeUrl.Insert(0, "~");
            if (!relativeUrl.StartsWith("~/")) relativeUrl = relativeUrl.Insert(0, "~/");
            var url = HttpContext.Current.Request.Url;
            var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
            return String.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
        }
        public static string GeneratePassword(int length) //length of salt    
        {
            const string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            var randNum = new Random();
            var chars = new char[length];
            var allowedCharCount = allowedChars.Length;
            for (var i = 0; i <= length - 1; i++)
            {
                chars[i] = allowedChars[Convert.ToInt32((allowedChars.Length) * randNum.NextDouble())];
            }
            return new string(chars);
        }
        public static string EncodePassword(string pass, string salt) //encrypt password    
        {
            byte[] bytes = Encoding.Unicode.GetBytes(pass);
           
            byte[] src = Encoding.Unicode.GetBytes(salt);
            byte[] dst = new byte[src.Length + bytes.Length];
            System.Buffer.BlockCopy(src, 0, dst, 0, src.Length);
            System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
            HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
            byte[] inArray = algorithm.ComputeHash(dst);
            //return Convert.ToBase64String(inArray);    
            return EncodePasswordMd5(Convert.ToBase64String(inArray));
        }
        public static string EncodePasswordMd5(string pass) //Encrypt using MD5    
        {
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;
            //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)    
            md5 = new MD5CryptoServiceProvider();
            originalBytes = Encoding.Default.GetBytes(pass);
            encodedBytes = md5.ComputeHash(originalBytes);
            //Convert encoded bytes back to a 'readable' string    
            return BitConverter.ToString(encodedBytes);
        }
        public static string base64Encode(string sData) // Encode    
        {
            try
            {
                byte[] encData_byte = new byte[sData.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }
        public static string base64Decode(string sData) //Decode    
        {
            try
            {
                var encoder = new System.Text.UTF8Encoding();
                System.Text.Decoder utf8Decode = encoder.GetDecoder();
                byte[] todecodeByte = Convert.FromBase64String(sData);
                int charCount = utf8Decode.GetCharCount(todecodeByte, 0, todecodeByte.Length);
                char[] decodedChar = new char[charCount];
                utf8Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decodedChar, 0);
                string result = new String(decodedChar);
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Decode" + ex.Message);
            }
        }
Posted
Updated 5-Apr-16 0:30am
v4

1 solution

Your Registration page changes

C#
<input type="text" class="form-control form-group" required="" name="EmailId" id="EmailId"> 
<input type="submit" id="btnSubmit" name="btnSubmit" onclick="validateform()" value="Submit" class="btn btn-primary pull-right" />

JavaScript
<script>
function validateform()
{
//FIND ALL CONTROL VALUE AND CHECK THROUGH AJAX POST BACK 
var Email= $("#EmailId").val();
$.ajax({
url: '@Url.Action("ACTION", "CONTROLLERNAME")', //check email if exist retrun false on success else return false 
type: "POST",
cache: false,
data: { Email:Email },
    success: function (data) {
     //retrun true/false;
     //You can show error message also
     },
    error: function (result) {
         
    }
})
}
</script>
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900