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.
public enum SampleEnum {
Active = 1, Inactive = 2, Pending = 3
}
public class SampleClass {
[Required]
public SampleEnum sampleEnum{get;set;}
}
<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,
you should make sure that you include the validation and unobtrusive libraries
jquery.validate.js
jquery.validate.unobtrusive.js
in your main layout view
if you don't have the files then you can install them from nuget
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