Search code examples
c#asp.net-mvchtml-helperasp.net-mvc-validation

ASP.NET MVC Html Helper: Adding a validation in an enum ddl


I'm pretty new in ASP.NET MVC. And I'm very sorry for this question.

What my goal is: To add a validation using Html Helper of ASP.NET MVC on an enum ddl.

Model

public enum SampleEnum { 
    Active = 1, Inactive = 2, Pending = 3
}
public class SampleClass { 
    [Required]
    public SampleEnum sampleEnum{get;set;}
}

View

<form action="url" method="post">
    @Html.EnumDropDownListFor(m => m.sampleEnum, "-- Select Sample Enum --", new { @class = "custom-select custom-select-sm" })
    @Html.ValidationMessageFor(m=> m.sampleEnum, "", new { @class = "text-danger" })
    <input type="submit" value="Submit" /> 
</form>

Once I clicked Submit, it doesn't validate my form but rather continue to submit it.
P.S. As much as possible, I would want to use model validation instead of jquery-validation.

Thanks,


Solution

  • you should make sure that you include the validation and unobtrusive libraries

    jquery.validate.js

    jquery.validate.unobtrusive.js

    in your main layout view

    enter image description here

    if you don't have the files then you can install them from nuget

    enter image description here

    Update : if you need only to use server side validation then you need just to Replace the data annotation for required field from [Required] to [Range(1, int.MaxValue, ErrorMessage = "This is required")] that's because @Html.EnumDropDownListFor will always send 0 if user didn't select any of the options of the drop down list, and that value will considered as valid. check this answer

    the filed decoration should look like the following enter image description here

    and please consider putting a valid action url for the form enter image description here