Met*_*urf 6 c# validation razor asp.net-mvc-3
如何使用MVC 3框架创建有条件的必需属性,该框架将在禁用JS时与客户端验证以及服务器端验证一起使用?例如:
public class PersonModel
{
[Required] // Requried if Location is not set
public string Name {get; set;}
[Range( 1, 5 )] // Requried if Location is not set
public int Age {get; set;}
[Required] // Only required if Name and Age are not set.
public string Location {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
此示例中的规则是:
Name
并且Age
如果Location
没有设置则是必需的.Location
仅在设置Name
和Age
未设置时才需要.在视图中,我需要将结果发送到Action
if Name/Age设置.并且设置了不同的Action
位置.我尝试了两种不同的Get Url的独立形式; 这很有效,除了验证规则导致问题.我希望使用2个单独的Get action Url,即
@model PersonModel
@using( Html.BeginForm( "Age", "Person", FormMethod.Post ) )
{
@Html.TextBoxFor( x => x.Name )
@Html.ValidationMessageFor( x => x.Name )
@Html.TextBoxFor( x => x.Age )
@Html.ValidationMessageFor( x => x.Age )
<input type="submit" value="Submit by Age" />
}
@using( Html.BeginForm( "Location", "Person", FormMethod.Post ) )
{
@Html.TextBoxFor( x => x.Location )
@Html.ValidationMessageFor( x => x.Location )
<input type="submit" value="Submit by Location" />
}
Run Code Online (Sandbox Code Playgroud)
基于PersonModel
上述情况,如果提交了Location,则验证将失败,因为PersonModel期望也设置Name和Age.而名称/年龄则相反.
鉴于上面的模拟示例,如何在禁用JS的情况下使用MVC 3框架创建条件要求的属性,该框架将与客户端验证以及服务器端验证一起使用?
您可以将自定义验证添加到您的模型中,无论是子类化ValidationAttribute
还是实现IValidatableObject
.
允许您通过 jQuery 实现和注册新的适配器和方法来ValidationAttribute
相对简单地添加客户端验证。IClientValidatable
请参阅执行自定义属性的客户端验证。
IValidatableObject
更适合无法重复使用的一次性验证要求。它还会导致代码稍微简单一些。不幸的是,没有简单的方法来使用此方法实现客户端验证。