Display login success and fail message using ViewBag in ASP.Net Core MVC

trisetia302
 
on Sep 25, 2021 04:29 AM
1081 Views

Hi,

I was succeed do validation for prevent user insert same user name when register, but I'm get problem to show alert message using "ViewBag.Message". The "ViewBag.Message" not show when process validation running.

I want is when user succeed register will show message like this ViewBag.Message = "Register New User successfully..";

And when user input same User Name will show message like this ViewBag.Message = "Opss User Name already exsist, Please try another User Name !!!";

Any help could be appreciate.

The Register.cshtml

@using Klinik_Apps.Models
@model LoginModel
@{
    ViewBag.Title = "Register";
    Layout = null;
}

<script src="~/assets/plugins/sweetalert2/sweetalert2.js"></script>
<link href="~/assets/plugins/sweetalert2/sweetalert2.css" rel="stylesheet" />
<link href="~/assets/css/fontawesome-free/css/all.css" rel="stylesheet" />
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<link href="~/css/StyleLogin.css" rel="stylesheet" />

<html>
<head>
    <title>Register</title>
</head>
<body>
    <div id="bg">
        <img src="~/assets/img/Register.jpg" class="img1" />
    </div>
    <form asp-action="Register" asp-controller="Login" method="post">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="container mt-2 img2">
            <div class="row">
                <div class="col-md-6">
                </div>
                <div class="col-md-4">
                    <div class="container_form">
                        <img src="~/assets/img/UserNew.jpg" height="204px" width="304px" />
                        <h6 class="text text-center alert alert-primary">
                            Hai User ! <br />
                            Welcome to Register New User
                        </h6>
                        <hr />
                        <div class="form-group">
                            <label for="UserName">
                                User Name
                            </label>
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="fa fa-user"></i></span>
                                <input asp-for="User_Name" id="User_Name" name="User_Name" class="form-control" placeholder="Enter User Name" required />
                                <br />
                                <span asp-validation-for="User_Name" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="Password">
                                Password
                            </label>
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="fa fa-key"></i></span>
                                <input type="password" asp-for="Password" class="form-control" placeholder="Enter Password" required />
                                <br />
                                <span asp-validation-for="Password" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="Email">
                                E-mail
                            </label>
                            <div class="input-group mb-3">
                                <span class="input-group-text"><i class="fa fa-envelope"></i></span>
                                <input type="email" asp-for="Email" class="form-control" placeholder="Enter E-mail" required />
                                <br />
                                <span asp-validation-for="Email" class="text-danger"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <div align="right">
                                <button type="submit" class="btn btn-md btn-success"><i class="fa fa-registered"></i> Register</button>
                            </div>
                        </div>
                        <i class="fa fa-arrow-alt-circle-left"> @Html.ActionLink("Back To Login Page", "Login")</i>
                    </div>
                </div>
            </div>
        </div>
    </form>

    @if (@ViewBag.Message != null)
    {
        <script type="text/javascript" lang="javascript">
        Swal.fire({
            position: 'top',
            icon: 'error',
            title: 'Oops...',
            text: '@ViewBag.Message'
        });
        </script>
    }
    <script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</body>
</html>

The Controller.cs

[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Register(LoginModel Register, string User_Name)
{
    try
    {
        if (User_Name != null)
        {
            Validation_Input_User_Name_Twice(Register, User_Name);
        }
        return View(Register);
    }
    catch (Exception)
    {
        throw;
    }
}
 
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult Validation_Input_User_Name_Twice(LoginModel Register, string User_Name)
{
    using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("Db_Klinik")))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            con.Open();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select User_Name From Tbl_User Where User_Name=@User_Name";
            cmd.Parameters.AddWithValue("@User_Name", User_Name);
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.HasRows)
                {
                    <span>ViewBag.Message = "Opss User Name already exsist, Please try another User Name !!!";</span>
                }
                else
                {
                    try
                    {
                        using (SqlConnection conn = new SqlConnection(this._configuration.GetConnectionString("Db_Klinik")))
                        {
                            using (SqlCommand cmdd = new SqlCommand())
                            {
                                conn.Open();
                                cmdd.Connection = conn;
                                cmdd.CommandType = CommandType.Text;
                                cmdd.CommandText = "Insert Into Tbl_User (User_Name,Password,Email) Values (@User_Name,@Password,@Email)";
                                cmdd.Parameters.AddWithValue("@password", Register.Password);
                                cmdd.Parameters.AddWithValue("@User_Name", Register.User_Name);
                                cmdd.Parameters.AddWithValue("@email", Register.Email);
                                cmdd.ExecuteNonQuery();
                                ViewBag.Message = "Register New User successfully..";
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
        }
    }
    return View();
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 25, 2021 06:46 AM

Hi trisetia302,

Refer below modified controller code.

[AllowAnonymous]
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Register(LoginModel Register, string User_Name)
{
    try
    {
        if (User_Name != null)
        {
            bool status = Validation_Input_User_Name_Twice(Register, User_Name);
            if (status)
            {
                ViewBag.Message = "Opss User Name already exsist, Please try another User Name !!!";
                return View("Register");
            }
            else
            {
                ViewBag.Message = "Register New User successfully..";
                return View("Register");
            }
        }
        return View(Register);
    }
    catch (Exception)
    {
        throw;
    }
}

private bool Validation_Input_User_Name_Twice(LoginModel Register, string User_Name)
{
    bool isExists = false;
    using (SqlConnection con = new SqlConnection(this._configuration.GetConnectionString("Db_Klinik")))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            con.Open();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Select User_Name From Tbl_User Where User_Name=@User_Name";
            cmd.Parameters.AddWithValue("@User_Name", User_Name);
            string name = Convert.ToString(cmd.ExecuteScalar());
            if (!string.IsNullOrEmpty(name))
            {
                isExists = true;
            }
            else
            {
                InsertUser(Register);
                isExists = false;
            }
            con.Close();
        }
    }

    return isExists;
}

private void InsertUser(LoginModel Register)
{
    try
    {
        using (SqlConnection conn = new SqlConnection(this._configuration.GetConnectionString("Db_Klinik")))
        {
            using (SqlCommand cmdd = new SqlCommand())
            {
                conn.Open();
                cmdd.Connection = conn;
                cmdd.CommandType = CommandType.Text;
                cmdd.CommandText = "Insert Into Tbl_User (User_Name,Password,Email) Values (@User_Name,@Password,@Email)";
                cmdd.Parameters.AddWithValue("@password", Register.Password);
                cmdd.Parameters.AddWithValue("@User_Name", Register.User_Name);
                cmdd.Parameters.AddWithValue("@email", Register.Email);
                cmdd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
}