I am using MVC5 with Razor views. My view model has a property of type nullable enum. I invalidated it, so when the user loads the page, they should select an option and check when they haven’t selected anything.
public class PaymentViewModel
{
[Required(ErrorMessage = "Please select a payment method", AllowEmptyStrings = false)]
public PaymentType? SelectedPaymentType { get; set; }
}
public enum PaymentType
{
CreditCard,
DirectDebit
}
In my opinion, I have a form and I invoke submit, which in turn invokes the controller action as a message.
The relevant part of my view is as follows:
<div class="row button-group" data-toggle="buttons">
<div class="col-xs-6">
<label class="btn btn-tertiary">
@Html.RadioButtonFor(model => model.SelectedPaymentType, PaymentType.CreditCard, new {@Name = "payment-method", @Value = "credit", @Id="rdoCredit"})
Credit Card
</label>
</div>
<div class="col-xs-6">
<label class="btn btn-tertiary">
@Html.RadioButtonFor(model => model.SelectedPaymentType, PaymentType.DirectDebit, new {@Name = "payment-method", @Value = "debit", @Id="rdoDebit"})
Direct Debit
</label>
</div>
</div>
For some reason, the value returning to my model. PaymentType is always null, although I selected the switch. I added the @Id attribute, as I noticed that it is assigned the same identifier if I did not specify it, but that did not help.
, , /.
, CreditCard ( ), DirectDebit radio , , CreditCard.
( , , ,
. html:
<form method="post" action="/myapplication/payment" novalidate="novalidate">
....
<div data-toggle="buttons" class="row button-group">
<div class="col-xs-6">
<label class="btn btn-tertiary">
<input type="radio" checked="checked" value="credit" name="payment-method" id="rdoCredit">
Credit Card
</label>
</div>
<div class="col-xs-6">
<label class="btn btn-tertiary">
<input type="radio" value="debit" name="payment-method" id="rdoDebit">
Direct Debit
</label>
</div>
</div>
...
</form>