0

I am creating a web app in asp.net mvc-5,

I am using IValidatableObject interface for validations,

here is how my model looks,

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

My view

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

My Controller

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

when my LicenseId = 0 then my validation is not working and the debugger on my controller is executing directly, but when LicenseId > 0 then my validation method is executing.

Ibrahim Shaikh
  • 388
  • 2
  • 18

1 Answers1

1

You need to manually add the validation inside your controller method.

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

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

EDIT

Well, 0 is a valid value for an int even if does not represent anything in your drop down. Try to change it to int?, then the default value would be null and it should be easier to catch it in model validation.

dbraillon
  • 1,742
  • 2
  • 22
  • 34