如何重新绑定 MVC Core 2 ModelState

How to Rebind MVC Core 2 ModelState

有没有办法在控制器中重新绑定模型状态验证?

我有以下内容:

        if (!model.DifferentShippingAddress)
        {
            model.ShippingAddress = model.BillingAddress.ToShipping();
            // Rebind modelstate
        }

        if (!ModelState.IsValid)
        {
            return View(model);
        }

如果选中 "SameAsBilling" 复选框,我想跳过 ShippingAddress 条目。

模型验证的 official documentation 内容如下:

Model validation occurs before the execution of a controller action.

因此,您需要清除 ModelState 并使用下面的代码手动触发验证。

if (!model.DifferentShippingAddress)
{
    model.ShippingAddress = model.BillingAddress.ToShipping();
    ModelState.Clear();
    TryValidateModel(model);
}