繁体   English   中英

模型中需要两个字段中的一个

[英]One field of the two will be required in Model

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

    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)
        {
        ...
        }..

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

有关自定义验证属性的更多信息: 如何为MVC创建自定义验证属性

尝试使用这种方法:

控制器:

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" />
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM