【问题标题】:One field of the two will be required in Model模型中需要这两个字段中的一个
【发布时间】:2012-10-30 00:36:02
【问题描述】:

我有一种情况,我想在模型中只需要两个字段中的一个。

    public int AutoId { get; set; }
    public virtual Auto Auto { get; set; }

    [StringLength(17, MinimumLength = 17)]
    [NotMapped]
    public String VIN { get; set; }

如果有人输入了 vin,它将在 AutoID 上的控制器中转换。如何强制控制器进行这样的工作?

         public ActionResult Create(Ogloszenie ogloszenie) {
        information.AutoId = 1;         
        if (ModelState.IsValid)
        {
        ...
        }..

【问题讨论】:

  • 抱歉,我有一个表格。在这种形式中,这两个字段。用户必须填写其中之一。需要填写一份。一个字段显示 AutoID,另一个显示 VIN。当用户填写 AutoID 时,一切正常。完成 VIN 时,ModelState.IsValid 为 false:(在检查 ModelState AutoID 字段之前完成。

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

您可以实现一个自定义验证属性,该属性将检查任一必填字段是否存在。

更多关于自定义验证属性:How to create custom validation attribute for MVC

【讨论】:

    【解决方案2】:

    尝试使用这种方法:

    控制器:

    public ActionResult Index()
    {
        return View(new ExampleModel());
    }
    
    [HttpPost]
    public ActionResult Index(ExampleModel model)
    {
        if (model.AutoId == 0 && String.IsNullOrEmpty(model.VIN))
            ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
        if (model.AutoId != 0 && !String.IsNullOrEmpty(model.VIN))
            ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
        if (ModelState.IsValid)
        {
            return null;
        }
        return View();
    }
    

    查看:

    @using(Html.BeginForm(null,null,FormMethod.Post))
    {
        @Html.ValidationMessage("OneOfTwoFieldsShouldBeFilled")
    
        @Html.TextBoxFor(model=>model.AutoId)
    
        @Html.TextBoxFor(model=>model.VIN)
        <input type="submit" value="go" />
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-12
      • 1970-01-01
      • 2017-04-22
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-29
      • 2021-03-04
      • 1970-01-01
      相关资源
      最近更新 更多