12

假设我有一个枚举:

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

1 回答 1

24

之所以选择它,是因为您的属性值StatusOrderStausType.Waiting(这就是绑定的工作原理!)。

new {@checked = true}从方法中移除@Html.RadioButtonFor()并在您的控制器中,在将其传递给视图之前将其值设置StatusOrderStausType.Shipped

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

@Html.RadioButtonFor(m => m.Status, OrderStausType.Picked, new {id = OrderStausType.Picked)
<label for=@OrderStausType.Picked>@OrderStausType.Picked</label>
于 2014-11-23T21:19:21.323 回答