I have a simple loginform based on the following modelitem
public class LogOnModelItem
{
[Required(ErrorMessage="Brukernavn er påkrevd")]
[DisplayName("Brukernavn")]
public string UserName { get; set; }
[Required(ErrorMessage="Passord er påkrevd")]
[DataType(DataType.Password)]
[DisplayName("Passord")]
public string Password { get; set; }
[DisplayName("Husk meg?")]
public bool RememberMe { get; set; }
}
The view is :
<h2>Login</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<table>
<tr>
<td>@Html.LabelFor(model => model.UserName)</td>
<td>
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</td>
</tr>
<tr>
<td>@Html.LabelFor(model => model.Password)</td>
<td>
@Html.EditorFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</td>
</tr> <tr>
<td>@Html.LabelFor(model => model.RememberMe)</td>
<td>
@Html.EditorFor(model => model.RememberMe)
@Html.ValidationMessageFor(model => model.RememberMe)
</td>
</tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
}
The controller:
public ActionResult Login(LogOnModelItem lmi)
{
return View(lmi);
}
When I load this up in the browser the validation is apparently run on pageload. This then outlines the username and password in red, with the error message supplied after each line. I have 3 questions for this, in order of importance:
1: How do I make sure the validation is not run until after the user presses submit.
2: How do I display the validation summary?
3: How do I make the “username” field choosen by default and ready to accept input?
Answer to #1:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LogOnModelItem lmi)
{
return View(lmi);
}
Answer to #2
@Html.ValidationSummary(false)
Answer to #3
<script type="text/javascript">
$(document).ready(function () {
$('#UserName').focus();
});
</script>
This should already be the case. If you have a GET action rendering this form and supplying a view model there won’t be any validation errors. It’s the POST action that would show the validation messages and if you have client validation enabled it could also happen
onblur.You already did:
@Html.ValidationSummary(true)You could use javascript: