如何使用Razor页面解开属性

发布于 2025-02-01 20:39:28 字数 874 浏览 1 评论 0原文

我使用剃刀页。
我在onpost方法中都有此属性

[BindProperty]
public ProductDto CreateProduct { get; set; }

,我检查modelState.isvalid,一切都可以。
但是,当我向我的处理程序发送请求时,我的处理程序OnPost方法验证将为false。
原因是modelState检查我的处理程序输入,还createProduct使用bind bind属性属性,当我发送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)
{
}

但是还有其他方法可以解决此问题。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

高跟鞋的旋律 2025-02-08 20:39:28

您可以使用要从modelstateDictionary中删除

ModelState.Remove("Password");

属性

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

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(
quot;{nameof(ProductDto)}.{prop.Name}");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文