首页 > 解决方案 > 始终从单选按钮中选择第一个枚举

问题描述

我有三个单选按钮,但是当我选择 EFG 并将其发布到控制器时,我总是在 Selected 属性中获得 ABC。

看法

@Html.RadioButtonFor(m => m.Selected, AllEnum.ABC) <label>ABC</label>
@Html.RadioButtonFor(m => m.Selected, AllEnum.EFG)<label>EFG</label>
@Html.RadioButtonFor(m => m.Selected, AllEnum.QWE)<label>QWE</label>

模型

public AllEnum Selected{ get; set; }

你能帮我在控制器中获取选定的单选按钮值吗?

标签: c#asp.netasp.net-mvc

解决方案


下面是工作代码。

模型

public enum AllEnum
{
    ABC,
    EFG,
    QWE
}

public class SimpleModel
{
    public AllEnum Selected { get; set; }
}

控制器

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        var model = new SimpleModel();

        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SimpleModel model)
    {
        return View(model);
    }
}

看法

@using SimpleMVC.Models
@model SimpleMVC.Models.SimpleModel

@using (Html.BeginForm())
{
    @Html.RadioButtonFor(m => m.Selected, AllEnum.ABC) <label>ABC</label>
    @Html.RadioButtonFor(m => m.Selected, AllEnum.EFG)<label>EFG</label>
    @Html.RadioButtonFor(m => m.Selected, AllEnum.QWE)<label>QWE</label>

    <input type="submit" />
}

推荐阅读