本文介绍了如何在输入的详细信息中显示登录表单的错误消息已存在于数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设计了两个表格的MVC-6应用程序,一个是注册表单,注册后我有另一个表单登录,注册时输入的用户名和密码相同。我提到的错误信息显示时注册相同的数据,所以错误信息没有显示.....



我期待如果我的数据库中已存在用户,则应显示错误消息因为用户已经存在......

请帮我解决一下这个问题......



先谢谢你,



我的尝试:



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:

---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---

@{
    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---

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---

// 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---

<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---


---here is my another helper class for password hash---

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);
            }
        }

推荐答案

Your Registration page changes




<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" />




<script>
function validateform()
{
//FIND ALL CONTROL VALUE AND CHECK THROUGH AJAX POST BACK 
var Email=




这篇关于如何在输入的详细信息中显示登录表单的错误消息已存在于数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 16:27