单选按钮 – MVC 5 RadioButtonFor枚举,始终选择默认的枚举值零?

前端之家收集整理的这篇文章主要介绍了单选按钮 – MVC 5 RadioButtonFor枚举,始终选择默认的枚举值零?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有一个枚举:
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,new {@checked = true})
<span>@OrderStatusType.Shipped</span>

@Html.RadioButtonFor(m => m.Status,OrderStatusType.Waiting)
<span>@OrderStatusType.Waiting</span>

解决方法

它的选择是因为您的属性状态的值是OrderStausType.Waiting(这是绑定如何工作!).

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

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

@Html.RadioButtonFor(m => m.Status,OrderStausType.Picked,new {id = OrderStausType.Picked)
<label for=@OrderStausType.Picked>@OrderStausType.Picked</label>
原文链接:https://www.f2er.com/html/224166.html

猜你在找的HTML相关文章