仅使用HTML

时间:2016-02-19 22:44:52

标签: asp.net-mvc validation

我正在联系我们表格,我能够成功验证,但我遇到了一个小问题,

当我提交并错过其中一个必需的值时,表单会返回错误消息并且不保留值,我注意到只有在我使用HTML时才会发生,它会与HTML帮助程序一起正常工作。 / p>

以下是我的代码片段:

<div class="form-group">
                        @Html.LabelFor(model => model.FirstName, "First Name")
                        <div>
                            <input class="form-control" name="FirstName" id="FirstName" data-val="true" type="text" value="" />
                            @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                        </div>
                    </div>

但它适用于姓氏字段:

<div class="form-group">
                        @Html.LabelFor(model => model.LastName, "Last Name")
                        <div>
                            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                        </div>
                    </div>

填写信息: filling the info

提交姓氏后请注意,但名字会消失: notice after submitting the last name stay there but the first name disappear

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:1)

因为输入标记的value属性值设置为空字符串。

您应该使用Html.TextBoxFor辅助方法生成输入字段,它会显示您在模型验证失败时发布的值。辅助方法还将生成客户端不显眼验证所需的相关html5属性。

@model ContactViewModel 
@using(Html.BeginForm())
{
   @Html.TextBoxFor(s=>s.FirstName)
   @Html.ValidationMessageFor(model => model.FirstName)
   <!-- Other fields -->
   <input type="submit" />               
}

假设您的HttpPost操作方法将已发布的模型返回到模型验证失败的视图

[HttpPost]
public ActionResult Contact(ContactViewModel model)
{
  if(ModelState.IsValid)
  {
     // to do : return something
  }
  return View(model);
}