如何在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?