I use razor pages.
I have this property
[BindProperty]
public ProductDto CreateProduct { get; set; }
In OnPost
Method, I check ModelState.IsValid
and everything is ok.
But when I send a request to my handlers that are next to my OnPost
method the validation will be false.
The reason is ModelState
check my handler inputs and also CreateProduct
that used bind property attribute, how can I unbind property that use BindProperty
attribute when I send request to the hanlders.
public IActionResult OnPostAddBrand(AddBrandDto model)
{
if (!ModelState.IsValid)
{
// AddBrandDto is valid but I got here.
Return Json(false);
}
// todo: SaveBrand
Return Json(true);
}
I know if I don't use BindProperty
attribute and get the object from the method inputs, problem will be solved, like this:
public ProductDto CreateProduct { get; set; }
public async Task<IActionResult> OnPost(ProductDto createProduct)
{
}
But is there any other way to solve this problem.
CodePudding user response:
You can use ModelState.Remove to remove properties from the ModelStateDictionary
e.g.
ModelState.Remove("Password");
If you want to "unbind" a complex property, you can use reflection to remove its properties:
foreach(var prop in ProductDto.GetType().GetProperties())
{
ModelState.Remove($"{nameof(ProductDto)}.{prop.Name}");
}