1
我有基於以下modelitem一個簡單的登錄表單如何停止在pageload上運行MVC3驗證腳本?
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; }
}
的觀點是:
<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>
}
控制器:
public ActionResult Login(LogOnModelItem lmi)
{
return View(lmi);
}
當我在瀏覽器中的驗證加載這個向上顯然是在頁面加載運行。然後將用戶名和密碼概括爲紅色,並在每行之後提供錯誤消息。我對此有3個問題,按重要程度排序:
1:如何確保直到用戶按下提交後才運行驗證。 2:如何顯示驗證摘要? 3:我如何使默認選擇的「用戶名」字段準備好接受輸入?
答案#1:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LogOnModelItem lmi)
{
return View(lmi);
}
答到#2
@Html.ValidationSummary(false)
回答#3
<script type="text/javascript">
$(document).ready(function() {
$('#UserName').focus();
});
</script>
1:訣竅是顯然有不帶參數的控制器操作,然後httppost行動。 – devzero 2011-03-16 12:55:44
2:這不起作用,我收到單個錯誤消息,但沒有總結。 – devzero 2011-03-16 12:57:06
你嘗試過傳遞'false'嗎? – 2011-03-16 13:00:33