我使用剃須刀頁面。
我有這個屬性
[BindProperty]
public ProductDto CreateProduct { get; set; }
在OnPost方法中,我檢查ModelState.IsValid并一切正常。
但是當我向我的OnPost方法旁邊的處理程式發送請求時,驗證將是錯誤的。
原因是ModelState檢查我的處理程式輸入以及使用系結屬性的屬性,當我向處理程式發送請求時CreateProduct,如何取消系結使用屬性的屬性。BindProperty
public IActionResult OnPostAddBrand(AddBrandDto model)
{
if (!ModelState.IsValid)
{
// AddBrandDto is valid but I got here.
Return Json(false);
}
// todo: SaveBrand
Return Json(true);
}
我知道如果我不使用BindProperty屬性并從方法輸入中獲取物件,問題將得到解決,如下所示:
public ProductDto CreateProduct { get; set; }
public async Task<IActionResult> OnPost(ProductDto createProduct)
{
}
但是有沒有其他方法可以解決這個問題。
uj5u.com熱心網友回復:
您可以使用ModelState.Remove從ModelStateDictionary例如洗掉屬性
ModelState.Remove("Password");
如果你想“解除系結”一個復雜的屬性,你可以使用反射來移除它的屬性:
foreach(var prop in ProductDto.GetType().GetProperties())
{
ModelState.Remove($"{nameof(ProductDto)}.{prop.Name}");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483901.html
