0

我在 asp.net mvc-5 中创建一个网络应用程序,

我正在使用 IValidatableObject 接口进行验证,

这是我的模型的外观,

public class LicenseInfo : IValidatableObject
{
    public int LicenseId { get; set; }
    //other properties

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        //Validate class which will be called on submit
    }
}

我的观点

@using (Ajax.BeginForm("_AddEditLicense", "User", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "dvLicenseContent", OnSuccess = "fnAddEditOnSuccess" }))
{
    @Html.ValidationSummary(false)
    @Html.DropDownListFor(m => m.LicenseId, new SelectList(Model.LicenseData, "Value", "Text"), "Select....", new { @class = "form-control" })

    @*other html elements*@
    <input type="submit" value="@ViewBag.Submit" id="btnaddLicense" class="btn btn-primary btn-block" />
}

我的控制器

[HttpPost]
public ActionResult _AddEditLicense(LicenseInfo data)
{
    if (ModelState.IsValid)
    {
        //execution
    }
}

当我LicenseId = 0的验证不起作用并且我的控制器上的调试器直接执行时,但是当LicenseId > 0我的验证方法正在执行时。

4

1 回答 1

1

您需要在控制器方法中手动添加验证。

[HttpPost]
public ActionResult _AddEditLicense(LicenseInfo data)
{
   if (ModelState.IsValid)
   {
      // Execute code
   }

   // Not validated, return to the view
   return View(data);
}

编辑

好吧,即使不代表下拉列表中的任何内容,0 也是 int 的有效值。尝试将其更改为 int?,则默认值为 null,在模型验证中应该更容易捕获它。

于 2019-07-05T10:17:18.777 回答