如何在MVC 3框架中使用客户端验证以及服务器端验证来禁用JS时如何创建条件所需的属性?例如:MVC 3有条件所需的属性
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;}
}
在这个例子中的规则是:
Name
和Age
如果Location
没有设置是必需的。Location
只有在未设置Name
和Age
时才需要。- 如果名称,年龄和位置均已设置,则无关紧要。
在视图中,如果设置了名称/年龄,则需要将结果发送到Action
。如果设置了位置,则会输入另一个Action
。我用两个不同的Get Url的独立表单进行了尝试;除非验证规则导致问题,否则这很有效。 Preferrably,我想使用2个独立的获取动作的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" />
}
基于上述PersonModel
,如果该位置被提交,验证将失败,因为PersonModel期待的姓名和年龄是也设置。反之亦然,名称/年龄。
鉴于上面的模拟的例子,你如何创建条件所需的属性与MVC 3框架,将与客户端验证以及服务器端验证时,禁用JS?