@ Html.ValidationMessageFor在用户输入之前显示错误消息

时间:2014-12-19 04:01:33

标签: asp.net asp.net-mvc

我有以下代码:

在模型中:

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能否以某种方式将此GET页面视为加载的POST页面,从而显示错误消息?我不确定为什么会这样,任何想法/想法都会很棒。

2 个答案:

答案 0 :(得分:0)

我在你的Html.Beginform()

中看到了一些问题

通常你应该写这个开始博客如下, 例如,如果您的控制器名称是Student,那么

@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)
}

答案 1 :(得分:-1)

您尚未指定将在Action上调用验证的表单方法 使用以下语法

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

相关问题