验证错误:值"on"对<< property name >>无效

use*_*982 12 c# asp.net-mvc asp.net-mvc-4

在我的项目中,我有一个模型,你可以在这里看到我模型的一部分:

public class CheckoutModel
{
    public bool OtherPlace { get; set; }

    [RequiredIf("OtherPlace", true, ErrorMessage = " ")]
    public string OtherPlaceFullName { get; set; }

    [RequiredIf("OtherPlace", true, ErrorMessage = " ")]
    public int OtherPlaceProvinceId { get; set; }

    [RequiredIf("OtherPlace", true, ErrorMessage = " ")]
    public string OtherPlaceCity { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我使用RequiredIf属性在视图中验证我的模型,

 if (!ViewData.ModelState.IsValid)
    {
        @Html.ValidationSummary(false)
    }
Run Code Online (Sandbox Code Playgroud)

我填写了我的表单的所有属性,但是当未填充OtherPlaceProvinceId时,我得到以下验证错误.

值"on"对于OtherPlace无效.

更新:控制器在这里:

    [HttpGet]
    public ActionResult CheckoutAccount()
    {
        var model = OrderManager.Instance.GetCheckoutAccount();
        return View("_CheckoutAccount", model);
    }

    [HttpPost]
    public ActionResult CheckoutAccount(CheckoutAccountModel model)
    {
        return View("_CheckoutAccount", model);
    }
Run Code Online (Sandbox Code Playgroud)

Sim*_*sey 35

OtherPlace是复选框吗?复选框的默认值是,on如果它被勾选,如果不是,则为空白.ModelBinder不理解这一点.

ASP.Net处理这个,如果你使用帮助,通过这样做:

<input type="checkbox" name="OtherPlace" value="true"/>
<input type="hidden" name="OtherPlace" value="false"/>
Run Code Online (Sandbox Code Playgroud)

模型绑定器现在将勾选出勾选的复选框,将其转换为布尔值并将其绑定到模型.

您还可以使用带有true/false值的单选按钮

  • 在asp核心中,我不需要添加隐藏字段. (2认同)
  • 是的,这就是我说“如果你使用助手”时的意思 (2认同)

Had*_*ifi -4

您应该将 OtherPlaceProvinceId 从 int 更改为 int?,

public int? OtherPlaceProvinceId { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • 仅当您可以为此字段发布空白值时才需要此操作 (2认同)
  • 这个答案实在是太没有意义了!它与答案中提到的问题有什么关系? (2认同)