如何使用razor页面解除属性绑定



我使用剃刀页。
我有这个属性

[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)
{
}

但是还有其他方法可以解决这个问题吗?

您可以使用ModelState。删除从ModelStateDictionary中删除属性,例如

ModelState.Remove("Password");

如果你想"unbind"对于复杂的属性,您可以使用反射来删除其属性:

foreach(var prop in ProductDto.GetType().GetProperties())
{
ModelState.Remove($"{nameof(ProductDto)}.{prop.Name}");
}

最新更新