我不明白为什么ModelState.isValid会以各种方式给我.我在电子邮件中设置了一些返回true并且我在空字段中输入,它也返回true.我的问题是,当该字段为空时,如果我写了这封电子邮件,我该怎么办?
我有下一个视图文件:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <div style="padding-top:5px;clear:both;"></div> <% using (Html.BeginForm()) { %> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Email usuario</legend> <div class="editor-field"> <%: Html.TextBoxFor(m => m.Email) %> <%: Html.ValidationMessageFor(m => m.Email) %> </div> <input type="submit" value="Enviar Email" /> </fieldset> <% } %> <div style="padding-top:5px;clear:both;"></div> </asp:Content>
控制器是:
// // GET: /Account/EmailRequest public ActionResult EmailRequest() { return View(); } [HttpPost] public ActionResult EmailRequest(string email) { if (ModelState.IsValid) { // save to db,for instance return RedirectToAction("AnotherAction"); } return View(); }
我的模型类是:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Web.Mvc; using System.Web.Security; namespace PortalClient.Models { public class EmailRequest { [required(ErrorMessage = "required")] public string Email { get; set; } } }
解决方法
将帖子操作的签名从字符串电子邮件更改为EmailRequest模型,然后检查状态.例如
[HttpPost] public ActionResult EmailRequest(EmailRequest model) { if (ModelState.IsValid) { // save to db,for instance return RedirectToAction("AnotherAction"); } return View(); }