ASP.Net MVC:仅在出现错误时才渲染Html.ValidationSummary

时间:2009-10-07 12:13:48

标签: asp.net-mvc

即使模型状态有效,仍会呈现Html.ValidationSummary()。

此示例不起作用:

<% if (!this.ViewData.ModelState.IsValid)
{ %>
<%= Html.ValidationSummary()%> 
<% } %>

仍然有一个空的'ul'标签被渲染。 如果ModelState无效,如何使其呈现

修改 事实证明ModelState确实是无效的,但是我的代码没有添加任何错误消息,它只是无效而没有明显的原因。

[AcceptVerbs("POST")]
public ActionResult Login(string username, string password, bool? remember)
    {
        if (string.IsNullOrEmpty(username))
        {
            ModelState.AddModelError("Username", "Username is required");
        }
        if (string.IsNullOrEmpty(password))
        {
            ModelState.AddModelError("Password", "Password is required");
        }

        if (ModelState.IsValid)
        {
            ; // this point is never reached
        }

        return View();
    }

3 个答案:

答案 0 :(得分:6)

如果您提供的信息正确无误,则this.ViewData.ModelState.IsValid绝对是错误的。这里必须有其他代码,你没有提供。

答案 1 :(得分:2)

source code表示当模型状态有效时,帮助器返回一个空字符串。我怀疑你的模型状态确实无效但是没有添加消息。或者,标记实际上可能来自您页面上的其他内容 - 甚至可能添加了javascript。

答案 2 :(得分:2)

在应用设置中检查ClientValidationEnabledUnobtrusiveJavaScriptEnabled。如果不使用它们,可以解决这个问题。

相关问题