Monday, June 20, 2016

Random password generator using Ajax in ASP.Net MVC

You can download the project from here : Download MVCPasswordExample 

As title says when user click a button it send ajax request to controller
$.post('@Url.Content("~/Home/GeneratePassword/")' ...
and returns Json with new 8 character password.


MODEL



public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { getset; }

        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        public string Email { getset; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { getset; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { getset; }
    }
  



VIEW


@{
    ViewBag.Title = "Home Page";
}

@using MVCPasswordExample.Models
@model RegisterModel

<script>
    $(document).ready(function () {
        $('#updateprofile').click(function () {
            $('form')[0].reset();

        });

        $('#autogenerate').click(function () {
            $.post('@Url.Content("~/Home/GeneratePassword/")'function (data) {

                $('#password, #confirmpassword').attr("value", data.password);

            });
        });

    });

</script>


<h2>@ViewBag.Message</h2>

<table style="margin-top:100px;width:40%">
 <tr>
 <th colspan="3">Change Password</th>
 </tr>


  <tr>
      <td>@Html.LabelFor(m => m.Password)
      </td>
     <td style="width:20%">
         @Html.TextBox("password"nullnew { @class = "search_field", @id = "password", @Value = "" })
     </td>
      <td><input type="button" id="autogenerate" value="Auto generate" class="submit_button" /></td>
 </tr>
    
  <tr>
      <td>
         @Html.LabelFor(m => m.ConfirmPassword)
      </td>
     <td class="confirm" colspan="2">
          @Html.TextBox("confirmpassword"nullnew { @class = "search_field", @id = "confirmpassword" })
      </td>

 </tr>


 </table>


CONTROLLER

        [HttpPost]
        public JsonResult GeneratePassword()
        {
           var pass = Guid.NewGuid().ToString().Substring(0, 8);


            return Json(new { password = pass });

        }

You can download the project from here : Download MVCPasswordExample