2014-12-19 163 views
1

之前我有以下代碼:@ Html.ValidationMessageFor顯示錯誤消息的用戶輸入

在模型:

public class Student { 

[Required(ErrorMessage = "name is a required field")] 
public string Name { get; set; } 

[Required(ErrorMessage = "school is a required field")] 
public string School { get; set; } 

} 

在控制器:

public ActionResult StudentView() 
{ 
return View(); 
} 

[HttpPost] 
public ActionResult StudentViewPost(Student model) 
{ 
if(ModelState.IsValid) 
{ 
.... 
.... 
} 
} 

而在我的視圖,我有:

@using (Html.BeginForm()){ 

@Html.TextBoxFor(model => model.Name) 
@Html.ValidationMessageFor(model => model.Name) 

@Html.TextBoxFor(model => model.School) 
@Html.ValidationMessageFor(model => model.School) 
} 

但是當我轉到視圖頁面時,即使在我有機會輸入任何輸入之前,驗證錯誤消息已經顯示(加載時)。有什麼理由可能會發生這種情況嗎? .NET能否以某種方式加載POST頁面時看到這個GET頁面,並顯示錯誤信息?我不知道爲什麼會發生這種情況,任何想法/想法都會很棒。

+0

發佈你'[HttpGet]'也有行動方法。 – 2014-12-19 04:46:38

+0

這不是默認行爲。其他的東西必須觸發驗證。除了'jquery - *。js'文件之外,你在頁面上有任何腳本嗎? – 2014-12-19 07:04:13

+0

我在頁面上的所有javascript都是jquery。 – Dan 2014-12-19 15:07:00

回答

0

我已經在你的Html.Beginform()看到了一些問題

通常情況下,你應該寫這個博客開始如下,如果 例控制器的名字是學生的話,

@using (Html.BeginForm("StudentViewPost", "Student", FormMethod.Post)) 
{ 
    @Html.TextBoxFor(model => model.Name) 
    @Html.ValidationMessageFor(model => model.Name) 

    @Html.TextBoxFor(model => model.School) 
    @Html.ValidationMessageFor(model => model.School) 
} 
+0

這將在OP使用情況下在窗體標籤中生成相同的輸出。它與驗證無關。 – 2014-12-19 07:04:41

-1

你沒有specifed以下形式方法,該方法將調用行動 使用驗證語法

@using (Html.BeginForm("ActionName", "Controller", FormMethod.Post)) { }

+0

這將在OP使用情況下在窗體標籤中生成相同的輸出。它與驗證無關。 – 2014-12-19 07:01:30