我在使用 ajax 表单验证时遇到问题(正如我所看到的许多人一样,但经过数小时的搜索,我仍然没有找到正确的答案)。
AJAX-post 没问题,我得到了我想要的响应,但是有两件事没有按计划工作:
- 客户端验证不起作用。
- 我的表单 DataType(DataType(DataType.EmailAddress)) 不起作用(type="text" 是我的属性,而不是 type="email")。
我在以下内容中包括<head>
:
<script src="@Url.Content("~/Scripts/jquery-2.0.0.min.js")"></script>
<script src="@Url.Content("~/Static/js/MicrosoftAjax.js")" type="text/javascript></script>
<script src="@Url.Content("~/Static/js/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"></script>
我的表单模型是:
public class EventForm
{
[Required(ErrorMessage = "First name must be filled")]
public string FirstName { get; set; }
[Required(AllowEmptyStrings = false,ErrorMessage = "Last Name must be filled")]
public string LastName { get; set; }
[DataType(DataType.EmailAddress)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Email must be filled")]
public string Email { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Compare("Email",ErrorMessage = "Email adress do not match")]
public string ConfirmEmail { get; set; }
[DataType(DataType.PhoneNumber)]
[Required(AllowEmptyStrings = false, ErrorMessage = "Phone number must be filled")]
public string PhoneNumber { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Company Name must be filled")]
public string CompanyName { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Adress must be filled")]
public string Adress { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Zip must be filled")]
public string Zip { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Postal city must be filled")]
public string PostalCity { get; set; }
public string Country { get; set; }
public string Comment { get; set; }
}
我的观点包含这种形式:
@using (Ajax.BeginForm("Index", new AjaxOptions() { HttpMethod = POST",
InsertionMode = InsertionMode.Replace, UpdateTargetId = "result" }))
{
<div id="result"></div>
{
Html.EnableClientValidation(true);
}
@Html.ValidationSummary(false)
@Html.ValidationMessageFor(p=>p.EventForm)
@Html.EditorFor(p=>p.EventForm)
}
最后,我的控制器:
public ActionResult Index(EventPage currentPage)
{
var model = new EventViewModel()
{
CurrentPage = currentPage,
EventForm = new EventForm()
};
return View(model);
}
[HttpPost]
public PartialViewResult Index(EventViewModel form)
{
return PartialView("PagePartial/FormSubmit", form.EventForm);
}
帮助?