Say I have an enum:
public enum OrderStatusType
{
Waiting = 0,
Pending,
Picked,
Shipped,
}
I generated the radio button list as follows.
@Html.RadioButtonFor(m => m.Status, OrderStatusType.Shipped, new {@checked = true})
@Html.RadioButtonFor(m => m.Status, OrderStatusType.Waiting)
But the Waiting is always selected. The output HTML is as below:
input type="radio" value="Shipped" name="Status" id="Status" checked="True"
input type="radio" value="Waiting" name="Status" id="Status" checked="checked"
Why is a "checked" attribute automatically added by MVC framework? Thanks.
The model:
public class OrderViewModel
{
public OrderStatusType Status { get; set; }
}
The view:
@using WebApplication17.Controllers
@model WebApplication17.Models.OrderViewModel
@{
ViewBag.Title = "Home Page";
}
@Html.RadioButtonFor(m => m.Status, OrderStatusType.Picked)
<span>@OrderStatusType.Picked</span>
@Html.RadioButtonFor(m=>m.Status, OrderStatusType.Pending)
<span>@OrderStatusType.Pending</span>
@Html.RadioButtonFor(m => m.Status, OrderStatusType.Shipped, new {@checked = true})
<span>@OrderStatusType.Shipped</span>
@Html.RadioButtonFor(m => m.Status, OrderStatusType.Waiting)
<span>@OrderStatusType.Waiting</span>
Its selected because the value of your property Status
is OrderStausType.Waiting
(that's how binding works!).
Remove new {@checked = true}
from the @Html.RadioButtonFor()
method and in your controller, set the value of Status
to OrderStausType.Shipped
before you pass it to the view.
Note also you should use a <label>
element rather that a <span>
to associate the label with the radio button
@Html.RadioButtonFor(m => m.Status, OrderStausType.Picked, new {id = OrderStausType.Picked)
<label [email protected]>@OrderStausType.Picked</label>