MVC 5 RadioButton为枚举,是否始终选择默认的枚举值零?

时间:2014-11-23 04:38:59

标签: radio-button html-helper asp.net-mvc-5.2

说我有一个枚举:

public enum OrderStatusType
{
    Waiting = 0,
    Pending,
    Picked,
    Shipped,        
}

我按如下方式生成了单选按钮列表。

@Html.RadioButtonFor(m => m.Status, OrderStatusType.Shipped, new {@checked = true})
@Html.RadioButtonFor(m => m.Status, OrderStatusType.Waiting)

但总是选择等待。输出HTML如下:

input type="radio" value="Shipped" name="Status" id="Status" checked="True"
input type="radio" value="Waiting" name="Status" id="Status" checked="checked"

为什么要检查""属性是否由MVC框架自动添加? 感谢。

模特:

public class OrderViewModel
{
    public OrderStatusType Status { get; set; }
}

观点:

@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>

1 个答案:

答案 0 :(得分:21)

选中它是因为您的属性Status的值为OrderStausType.Waiting(这就是绑定的工作原理!)。

new {@checked = true}方法和控制器中删除@Html.RadioButtonFor(),将Status的值设置为OrderStausType.Shipped,然后再将其传递给视图。

另请注意,您应该使用<label>元素而不是<span>来将标签与单选按钮相关联

@Html.RadioButtonFor(m => m.Status, OrderStausType.Picked, new {id = OrderStausType.Picked)
<label for=@OrderStausType.Picked>@OrderStausType.Picked</label>