【问题标题】:Ussing error prompts in asp/mvc application在 asp/mvc 应用程序中使用错误提示
【发布时间】:2011-07-26 11:53:58
【问题描述】:

我一直在寻找一种直接的方式来提示错误消息,最好是弹出窗口,(javascript 或其他)给在此表单上登录系统失败的用户:

@model Blog.Models.ViewModels.LoginView
<!DOCTYPE html>
<html>
<body>
@using (Html.BeginForm()) {
<p>Your name: @Html.TextBoxFor(x => x.name) </p>
<p>Your password: @Html.TextBoxFor(x => x.password)</p>
    <input type="submit" value="Login" />    
}
</body>
</html>

但我发现的大多数示例都在标签上使用 onclick 方法。相反,我希望它由这个控制器处理:

private BlogModel model = new BlogModel();
[HttpPost]
    public ActionResult LoginForm(string name, string password)
    {
                SysUser user = model.SysUsers.Where(x => x.SysUserName == name).First();
                {
                    if (user != null && user.SysPassword == password)
                    {
                        Session["usrn"] = name;
                        return RedirectToAction("LoginSuccessful", "Users");
                    }
                    else
                    {
                        //display error//
                    }
                }

【问题讨论】:

  • 使用Ajax.BeginForm()而不是Html.BeginForm()
  • 在 TempData 的页面中添加一点脚本

标签: c# javascript asp.net asp.net-mvc-3


【解决方案1】:

我建议不要弹出或 alert() 对话框。相反,我会使用样式化的 div 来显示您的错误消息。如果你使用 jQuery UI,你可以试试我的message plugin。由于它是用 javascript 显示的,因此您可以像这样使用它:

控制器:

[HttpPost]
public ActionResult LoginForm(string name, string password)
{
    SysUser user = model.SysUsers.Where(x => x.SysUserName == name).First();
    {
        if (user != null && user.SysPassword == password)
        {
            Session["usrn"] = name;
            return RedirectToAction("LoginSuccessful", "Users");
        }
        else
        {
            ViewBag.LoginError = true;
        }
    }
}

使用 jquery-message 标记:

<div id="loginError" style="display:none">Login Error...</div>

@if (ViewBag.LoginError == true)
{
    <script type="text/javascript">
        $("#loginError").message({type:"error"});
    </script>
}

或者,如果您愿意,也可以不使用 jquery-message:

@if (ViewBag.LoginError == true)
{
    <div id="loginError" class="error">Login Error...</div>
}

【讨论】:

  • 是的,谢谢 jrummell,这正是我所需要的。我只需要在控制器上添加一个新操作,在其中定义 LoginError 如下所示:public ActionResult LoginFailed() { ViewBag.LoginError = true; return View("LoginForm"); } 然后重定向到该操作,否则 LoginForm 操作不会有输出,但现在它可以工作了!
猜你喜欢
  • 1970-01-01
  • 2017-11-30
  • 2021-12-02
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
相关资源
最近更新 更多