0

What I want is, I have written a function for Validating user login credentials on server side. So what I am not getting is, I want to prompt a message if user has entered a invalid credentials.

Below is the Code for Validation.

public ActionResult ValidateUser()
    {
        string strUsername = Convert.ToString(Request.Form["txtUsername"]);
        string strPassword = Convert.ToString(Request.Form["txtPassword"]);
        //  return   RedirectToAction("Assign","App");
        string strReturn = "";
        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 = ObjUMS.AuthenticateUser(strUsername, strPassword, out strDbError);

        Session["isUserAuthenticated"] = result;

        try
        {
            if (result == true)
            {
                Session["isUserOutsideINDomain"] = true;
                Session["OutsideINDomainUsername"] = strUsername;
                //redirect to respective controller

                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();
                        Session["LoginUserName"] = strUsername.ToUpper();
                        TempData["Location"] = lstUMSLocationDetails;
                        Session["strCurrentGroupName"] = strCurrentGroupName;
                        TempData["strCurrentGroupName"] = strCurrentGroupName;
                        TempData.Keep();
                    }
                    else
                    {
                        return RedirectToAction("Error", "Shared");
                        //action = "ErrorPage"; controller = "UnAutherized";      
                        TempData["strLoginErrorInfo"] = "Invalid Username or Password";
                        TempData.Keep();
                    }
                }
            }

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

        }
        catch (Exception ex)
        {
            ApplicationLog.Error("Error", "ValidateUser", ex.Message);
        }
        return RedirectToActionPermanent(action, controller);
    }

Please suggest where I can prompt in my above code.

2
  • 1
    What do you mean by prompt here? If you want to send back a prompt you can do something like return Json("Invalid Credentials", JsonRequestBehavior.AllowGet); if you are using AJAX to post to your function. If you are using a model binding, you can use ModelState.AddModelError("Error", "Invalid Credentials"); return View(viewModel); Commented Mar 28, 2019 at 6:17
  • @RahulSharma: Thanks for the comment, can you post in an answer section. so it could be visible properly Commented Mar 28, 2019 at 7:19

1 Answer 1

3

There are different ways in which you can send your message prompts back to the View from your Controller:

If you are using AJAX to POST to your Controller, you could use a JSON response. An example of this would be:

$.ajax({
 //You AJAX code....
 //On success
 success: function (data){
   if (data == "Invalid") {
     alert("Invalid Credentials Supplied");
  }
 },
 //If there is any error
 error: function (data) {
 alert("Could not process your request.");
 },
});

And in your Controller:

public ActionResult ValidateUser()
{
//Your logic
return Json("Invalid", JsonRequestBehavior.AllowGet);
}

OR

You can use ViewData or ViewBag also to set your prompt messages. An example would be:

On your View:

<script type="text/javascript">
    $(document).ready(function () {
        var yourPrompt= '@ViewBag.PromptMessage';
        alert(yourPrompt);
    });
</script>

In your Controller, you can setup your prompt:

ViewBag.PromptMessage= "Invalid Credentials Supplied";

Alternatively using ViewData with a conditional statement:

<script type="text/javascript">
    $(document).ready(function () {

        var yourPrompt= '@ViewData["PromptMessage"]';
        if(yourPrompt=="Invalid"){
        alert("Invalid Credentials supplied");
       }        
    });
</script>

In your Controller, you can setup your prompt:

ViewData["PromptMessage"] = "Invalid";

OR

You could use ModelState to display your prompts or errors on your View. This is used when you are using a strongly typed Model-View binding in your Controller. An example:

In your View, setup your ValidationSummary:

@Html.ValidationSummary(false, "", new { @class = "text-danger" })

By default, ValidationSummary filters out field level error messages. The following will display error messages as a summary at the top. Please make sure that you don't have a ValidationMessageFor method for each of the fields in your model. These are for specific fields only.

You can also display a custom error message using ValidationSummary. To display a custom error message, first of all, you need to add custom errors into the ModelState in the appropriate action method.

In your Controller:

public ActionResult DoSomething()
{
  //Your condition where you want to show your message
  //Add to the model state, your custom error 
  ModelState.AddModelError(string.Empty, "Invalid Credentials Supplied")
  return View("Your View Name");
}

Addition:

If you want to customize the styling of your error message in your View, add a class to your ValidationSummary like this @Html.ValidationSummary(false, "", new { @class = "text-danger" }). Then you can use this class in your CSS like this:

.text-danger
{ 
/*Your style*/
}
Sign up to request clarification or add additional context in comments.

7 Comments

I tried the last one with my current above code, but it was not prompting the message which was suppied. any help
The ModelState one? Did you try the ViewData method?
No I didnt tried the viewdata. i added like this else { ModelState.AddModelError(string.Empty, "Invalid Username and password supplied"); } but no prompt
Did you add ValidationSummary in your View? The last method is for strongly typed Model-View binding. I would suggest you to go with ViewData or ViewBag method
Thanks Rahul for your answer
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.