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

Ego*_*hin 9 asp.net-mvc

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

此示例不起作用:

<% if (!this.ViewData.ModelState.IsValid)
{ %>
<%= Html.ValidationSummary()%> 
<% } %>
Run Code Online (Sandbox Code Playgroud)

仍然会呈现一个空的'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();
    }
Run Code Online (Sandbox Code Playgroud)

spe*_*der 6

如果您提供的信息是正确的,那么this.ViewData.ModelState.IsValid绝对是错误的.这里必须有其他代码,您不提供.