3

I created a login page based on the user model, the user has additional required fields apart from username and password (e.g. e-mail address) but I'm only displaying username and password for login.

The problem is that if I leave username and/or password empty, the ModelState is getting error messages for all fields within the Model class, resulting in misleading validation messages.

The code for the view is:

<div class="form-login">
@using (Html.BeginForm())
{
    <h2 class="form-signin-title">Login</h2>
    <div class="editor-label">
        @Html.LabelFor(model => model.Username)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Username)
        @Html.ValidationMessageFor(model => model.Username)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Password)
    </div>
    <div class="editor-field">
        @Html.PasswordFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)
    </div>
    <button class="btn btn-medium btn-primary" type="submit">Login</button>
}

The validation summary is part of the _Layout, and is only displayed if the model is not valid.

Is there a way I can show a validation summary for the controls on screen only?

4

1 回答 1

1

显示验证错误消息是因为 asp.net MVC 验证验证了视图模型。因此,是否在视图中显示字段并不重要,因为模型作为一个整体已经过验证。您应该为此表单使用仅包含显示字段的专用视图模型。

于 2013-02-28T08:57:05.067 回答