0

I have added a check and validation where if a user adds an invalid username and password, then the system prompts message.

But what I want is, I want to remove that message if user again goes and try to insert the username and password. Currently, the message doesn't go away.

Code:

[HttpPost]
[ValidateInput(false)]
public ActionResult ValidateUser() {
  string strUsername = Sanitizer.GetSafeHtmlFragment(Convert.ToString(Request.Form["txtUsername"]));
  string strPassword = Sanitizer.GetSafeHtmlFragment(Convert.ToString(Request.Form["txtPassword"]));
  string strDbError = string.Empty;
  strUsername = strUsername.Trim();
  strPassword = strPassword.Trim();
  string strUserName = "";
  string strCurrentGroupName = "";
  int intCurrentGroupID = 0;
  string controller = "";
  string action = "";

  UserProviderClient ObjUMS = new UserProviderClient();
  bool result = false;

  if (strUsername != "" || strPassword != "") {
    result = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);
    try {
      if (result == true) {
        UMS ObjUMSDATA = new UMS();
        //strUserName = System.Web.HttpContext.Current.User.Identity.Name.Split('\\')[1];
        strUserName = strUsername;
        _UMSUserName = strUserName;

        if (!string.IsNullOrEmpty(strUserName)) {
          List < UMSGroupDetails > lstUMSGroupDetails = null;
          List < UMSLocationDetails > lstUMSLocationDetails = null;

          ObjUMSDATA.GetUMSGroups(strUserName, out strCurrentGroupName, out intCurrentGroupID, out lstUMSLocationDetails, out lstUMSGroupDetails);
          if (strCurrentGroupName != "" && intCurrentGroupID != 0) {
            ViewBag.LoginUserName = strUserName.ToUpper();
            ViewBag.CurrentGroupName = strCurrentGroupName;
            ViewBag.CurrentGroupID = intCurrentGroupID;
            ViewBag.GroupDetails = lstUMSGroupDetails;
            ViewBag.LocationDetails = lstUMSLocationDetails;
            TempData["LoginUserName"] = strUsername.ToUpper();
            TempData["Location"] = lstUMSLocationDetails;
            TempData["strCurrentGroupName"] = strCurrentGroupName;
            TempData.Keep();
          } else {
            ModelState.AddModelError(string.Empty, "You are not registered. Please register first.");
            return View("Login");
          }
        }
      }
      if (strCurrentGroupName == "SAP Executive") {
        action = "Assign";
        controller = "App";
      } else if (strCurrentGroupName == "Maintenance Lead") {
        //return RedirectToAction("App", "Certify");
        action = "Certify";
        controller = "App";
      } else if (strCurrentGroupName == "NEIQC CMM") {
        //return RedirectToAction("App", "Approver");
        action = "Approver";
        controller = "App";
      } else {
        ModelState.AddModelError(string.Empty, "Invalid Username and password");
        return View("Login");
      }
    } catch (Exception ex) {
      ApplicationLog.Error("Error", "ValidateUser", ex.Message);
    }
  } else {
    ModelState.AddModelError(string.Empty, "Invalid Username and password");
    return View("Login");
  }

  //Session["isUserAuthenticated"] = result;            
  return RedirectToActionPermanent(action, controller);
}

HTML:

<div class="loginForm" id="loginForm" ng-controller="UserSelection">

  @using (Html.BeginForm("ValidateUser", "Home", FormMethod.Post)) {

  <div class="formGroup hide1">
    <input type="text" id="txtUsername" class="formInput" name="txtUsername" ng-model="LoginUserName" />
    <span class="focusInput" data-placeholder="Username"></span>
  </div>
  <div class="password formGroup hide1">
    <input type="password" id="txtPassword" class="formInput" name="txtPassword" ng-model="LoginPassword" />
    <span class="focusInput" data-placeholder="Password"></span>
  </div>
  <div class="submit formGroup hide1">
    @*<button type="button" id="submit" onclick="return validateUser();">Submit</button>*@
    <button type="submit" id="submit" ng-disabled="(!LoginUserName||!LoginPassword)" onclick="return submitLogin();" class="loginUser"><i class="fa fa-refresh fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading...</span> Submit</button>
  </div>
  <div class="error">
    @Html.ValidationSummary(false, "", new { @class = "text-danger " })
  </div>
  <div class="ums">
    <a href="#" target="_blank" title="Contact Jio.GISOperations@ril.com for registration and support.">Register</a>
  </div>
  @*
  <div class="ums"><a href="#" target="_blank">Register</a></div>*@ }
</div>

Above is my code, please suggest where I am wrong.

DavidG
  • 113,891
  • 12
  • 217
  • 223
Nad
  • 4,605
  • 11
  • 71
  • 160
  • Possible duplicate of [How do I clear MVC client side validation errors when a cancel button is clicked when a user has invalidated a form?](https://stackoverflow.com/questions/2798427/how-do-i-clear-mvc-client-side-validation-errors-when-a-cancel-button-is-clicked) – Rafael Herscovici Jun 03 '19 at 09:22
  • @Dementic: so as per you, I have to change all my logic and write the code as per given in the link. As you can clearly see the code given is in javascript – Nad Jun 03 '19 at 09:24
  • if you only bothered to see the link, you will clearly see the solution is a JS function to reset the validation. the validation errors you display, are on the FrontEnd, which means you need JS to remove them, or, to submit the form again. – Rafael Herscovici Jun 03 '19 at 09:26
  • 1
    Side question: What is `Sanitizer.GetSafeHtmlFragment` and why are you not using standard MVC methods? – DavidG Jun 03 '19 at 09:26
  • @DavidG: I have added that for `XSS attacks`. Cross site scripting – Nad Jun 03 '19 at 09:27
  • Side Note: you can use `switch (strCurrentGroupName)` instead of the chained `if` statements. – Rafael Herscovici Jun 03 '19 at 09:31
  • @Dementic: Oh I see, but on which event I should write it ? – Nad Jun 03 '19 at 09:34
  • Probably on `keyup` event of the both the inputs (user & pass) – Rafael Herscovici Jun 03 '19 at 09:42
  • @Dementic: I tried adding like this `ModelState.AddModelError(string.Empty, "Invalid Username and password"); ModelState.Clear(); return View("Login");` but first the message not displayed only – Nad Jun 03 '19 at 09:54
  • 1
    How could that possibly stop XSS attacks? MVC already includes features to prevent them, why not use them? – DavidG Jun 03 '19 at 10:16
  • @DavidG: if u dont mind, can u show that method ?? – Nad Jun 03 '19 at 10:17
  • What you want is that the errors should be cleared when the user is typing in the text boxes for username and password but you need to understand that validation fires on `Form` Submit and if you want to reset the validation message before form submit then you can clear it manually by resetting the class attribute. An example is here: https://stackoverflow.com/questions/5457393/reset-mvc-form-with-jquery – Rahul Sharma Jun 03 '19 at 12:11

1 Answers1

0

Please try the below code.

   <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        $(function () {
            $('#txtUserName').blur(
                function () {
                    $('.validation-summary-errors').remove();
                });
        });
    </script>
Skaria Thomas
  • 419
  • 3
  • 10