【发布时间】:2011-11-12 04:46:59
【问题描述】:
当禁用 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;}
}
本例中的规则是:
-
如果未设置
Location,则需要Name和Age。 -
仅当未设置
Name和Age时才需要Location。 - 无论姓名、年龄和位置是否都已设置。
在视图中,如果设置了名称/年龄,我需要将结果发送到Action。如果设置了位置,则为不同的Action。我尝试过使用 2 种不同 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" />
}
根据上面的PersonModel,如果提交了位置,验证将失败,因为 PersonModel 期望同时设置名称和年龄。姓名/年龄反之亦然。
鉴于上述模拟示例,您如何使用 MVC 3 框架创建条件要求的属性,以便在禁用 JS 时与客户端验证以及服务器端验证一起使用?
【问题讨论】:
标签: c# asp.net-mvc-3 validation razor