2014-12-19 139 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