Reputation: 206
I am displaying radio buttons using enum class.
public enum RegisteredBy
{
[Display(Name = "Customer", Order = 0)]
H,
[Display(Name = "Dealer/Contractor", Order = 1)]
S,
}
When i am rendering this on my view and on submit I am not selected any radio button. Even though it is taking "H"
as default value. So that it is not showing any validation message.
@using ConsumerProductRegistration.Models;
@using ProductRegistration.Models.Enums;
@model ProductRegistration.Models.Registration
@Html.RadioButtonFor(m => m.RegisteredBy, RegisteredBy.H, new { id = "RegisteredByCustomer" })
@Html.Label("Customer")<br />
@Html.RadioButtonFor(m => m.RegisteredBy, RegisteredBy.S, new { id = "RegisteredByDealer" })
@Html.Label("Dealer/Contractor")
@Html.ValidationMessageFor(m => m.RegisteredBy)
In Model:
public class Registration
{
[Required(ErrorMessage = "Select at least one option")]
[Display(Name = "Registered by*")]
public RegisteredBy RegisteredBy { get; set; }
}
In view:
public ActionResult CustomerInfo(Registration registration)
{
return View(registration);
}
please suggest me.If user does not select we should show the error message.
Upvotes: 2
Views: 1967
Reputation: 5331
The default underlying type of the enumeration elements is int
. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
When you are not selecting anything and posting the form, the default value 0 is automatically getting set (default value of integer).
In this case, you can make your property nullable with [Required]
attribute which sends null as value when nothing is selected. And as it is decorated with [Required]
attribute, it will give you required field validation error.
[Required]
public RegisteredBy? RegisteredBy { get; set; }
Upvotes: 2