由于某种原因,我无法获得Url.Action来触发MVC 2中的客户端验证。
<div class="createpage"><a href="<%= Url.Action("Create","Account") %>"></a></div>
其中“创建”是操作,“主页”是控制器(AccountController.cs)。如果我按常规的提交按钮,则验证将非常完美。我有这样的验证设置
<% using (Html.BeginForm())
{%>
<%= Html.ValidationSummaryJQuery(
"Please fix the following errors.",
new Dictionary<string, object> { { "id", "valSumContainer" /* This is important. You can change the "id" attribute value, but don't remove it */ } }) %>
<% ViewContext.FormContext.ValidationSummaryId = "valSumContainer"; { %>
//Form here
<%}%>
验证设置来自here
我从中获取验证消息的RegistrationModel.cs看起来像这样
[PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")]
public class RegistrationModel
{
[Required(ErrorMessage = "Username is required")]
[StringLength(25, ErrorMessage = "Username cannot be longer than 25 characters")]
public string Username { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public AccountType AccountType { get; set; }
[Required(ErrorMessage = "Studio Name is required.")]
public string StudioName { get; set; }
[Required(ErrorMessage = "Phone number is required")]
[PhoneNumber(ErrorMessage="Not a valid phone number")]
public string PhoneNumber { get; set; }
[Required(ErrorMessage = "Email address is required")]
[Email(ErrorMessage = "Not a valid email address")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "City is required")]
public string City { get; set; }
[UIHint("StatesDropDown")]
[Required(ErrorMessage="State is required")]
public string State { get; set; }
[Required(ErrorMessage = "Zip code is required")]
[StringLength(10, ErrorMessage = "Zip code canot be longer than 10 digits")]
[ZipCode(ErrorMessage="Invalid zip code")]
public string ZipCode { get; set; }
[Required(ErrorMessage = "About text is required")]
public string AboutText { get; set; }
[Required(ErrorMessage = "Starting price is required")]
[Currency(ErrorMessage="Not a valid currency value")]
public double PriceStartsAt { get; set; }
[UIHint("SkillsListView")]
[Required(ErrorMessage="At least 1 skill must be selected")]
public IList<Skill> Skills { get; set; }
[UIHint("EquipmentListView")]
[Required(ErrorMessage = "At least 1 equipment must be selected")]
public IList<Skill> Equipment { get; set; }
[UIHint("OccassionsListView")]
[Required(ErrorMessage = "At least 1 occassion must be selected")]
public IList<Skill> Occassions { get; set; }
}
就像我说的那样,使用普通的提交按钮就可以正常工作(但是客户端需要其UI,因此按钮必须在CSS中使用某些图像精灵。
编辑:放置HomeController而不是AccountController,已修复
最佳答案
@PsychoCoder
在Web上,仅在提交表单时才触发验证。
如果您想使用锚标记进行验证,则需要设置一些JavaScript代码。此javascript可以是jQuery验证库,也可以使用锚点上的onclick事件调用提交。<a href="javascript:void(0);" onclick="this.form[0].submit()">Create</a>
“ this.form [0]”可以替换为创建表单的ID。