必需的字段驗證未觸發。MVC必需的字段驗證不起作用
型號:
public class Client
{
[Required(ErrorMessage="Name Required")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Name { get; set; }
public string Address { get; set; }
public string Mobile { get; set; }
public string Telephone { get; set; }
public string Fax { get; set; }
public string Company { get; set; }
}
控制器:
[HttpPost]
public ActionResult Create(Client client)
{
try
{
// TODO: Add insert logic here
ClientRepository rep = new ClientRepository();
rep.AddClient(client);
rep.Save();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
查看:
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Add New Client</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Address) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Address) %>
<%: Html.ValidationMessageFor(model => model.Address) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Mobile) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Mobile) %>
<%: Html.ValidationMessageFor(model => model.Mobile) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Telephone) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Telephone) %>
<%: Html.ValidationMessageFor(model => model.Telephone) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Fax) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Fax) %>
<%: Html.ValidationMessageFor(model => model.Fax) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Company) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Company) %>
<%: Html.ValidationMessageFor(model => model.Company) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
** [爲什麼服務器端驗證,而不是客戶端(http://stackoverflow.com/a/16245682/2007801)** – 2013-05-01 20:13:07
@ user2007801從記錄上來看,你絕不能在用戶信任輸入。客戶端驗證可以被禁用 - 操縱 - 僞造等,所以服務器端驗證總是必要的。 – Oscar 2014-09-10 20:23:48