簡體   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