1
我創建了一個asp.net應用程序與以下域實體:Asp.net MVC深驗證
public class Person
{
[Required]
public string name { get; set; }
public string address { get; set; }
public ICollection<Item> ItemsPurchased { get; set;}
}
public class Item
{
[Required]
public string name { get; set; }
public int price { get; set; }
}
與視圖模型
public class PersonViewModel
{
public Person Entity { get; set; }
public Item ItemPurchased { get; set; }
}
現在我有一個要求輸入一個形式的人的細節以及購買的物品(如果有)
Html.Label("Person Name")
Html.TextboxFor(model => model.Entity.name)
Html.ValidationMessageFor(model => model.Entity.name)
Html.Label("Item Name")
Html.TextboxFor(model => model.ItemPurchased.name)
Html.ValidationMessageFor(model => model.ItemPurchased.name)
Html.Label("Item Price")
Html.TextboxFor(model => model.ItemPurchased.Price)
Html.ValidationMessageFor(model => model.ItemPurchased.Price)
最後在控制器中,我要添加項目(如果它是給n由用戶)添加到集合中。
if(!this.ModelState.IsValid)
{
//Return the view with validation errors
}
主要問題
現在,如果不給項目名稱的價值,它給了我「這個名字字段是必需」的驗證錯誤。但是我想僅刪除此表單的項目對象屬性的驗證。我怎樣才能做到這一點?