使用MVC代码显示无效的登录详细信息消息

时间:2019-03-28 06:01:34

标签: c# asp.net-mvc model-view-controller

我想要的是,我编写了一个用于在服务器端验证用户登录凭据的功能。所以我没有得到的是,如果用户输入了无效的凭据,我想提示一条消息。

下面是验证码。

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

请建议我在上面的代码中可以提示的地方。

1 个答案:

答案 0 :(得分:3)

您可以通过多种方式将消息提示从控制器发送回视图:

如果您使用AJAX POST到Controller,则可以使用JSON响应。例如:

$.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.");
 },
});

在您的控制器中:

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

OR

您也可以使用ViewDataViewBag来设置提示信息。一个例子是:

在您的视图上:

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

在您的控制器中,您可以设置提示:

ViewBag.PromptMessage= "Invalid Credentials Supplied";

或者将ViewData与条件语句一起使用:

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

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

在您的控制器中,您可以设置提示:

ViewData["PromptMessage"] = "Invalid";

OR

您可以使用ModelState在视图上显示提示或错误。当您在Controller中使用强类型的Model-View绑定时,将使用此方法。一个例子:

在您的视图中,设置您的ValidationSummary

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

默认情况下,ValidationSummary过滤掉字段级别的错误消息。下面将在顶部以摘要形式显示错误消息。请确保您没有模型中每个字段的ValidationMessageFor方法。这些仅用于特定字段。

您还可以使用ValidationSummary显示自定义错误消息。要显示自定义错误消息,首先,您需要使用适当的操作方法将自定义错误添加到ModelState中。

在您的控制器中:

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

添加:

如果您想在视图中自定义错误消息的样式,请像@Html.ValidationSummary(false, "", new { @class = "text-danger" })这样向您的ValidationSummary添加一个类。然后,您可以像下面这样在CSS中使用此类:

.text-danger
{ 
/*Your style*/
}