如何在ASP.NET MVC 5中正确显示单选按钮 [英] How to correctly display radiobutton in asp.net mvc 5

查看:0
本文介绍了如何在ASP.NET MVC 5中正确显示单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在ASP.NET MVC 5应用程序中显示一组单选按钮的最佳方式。

尝试1:

    @Html.RadioButton("SearchBy", "Name", true) <text> Name </text>
    @Html.RadioButton("SearchBy", "Location") <text> Location</text>


    [HttpPost]
    public ActionResult Create(CoverLetterViewModel viewModel, string searchBy)
    {//somecode}

尝试2:

     //prop
       public string SelectedRoleType { get; set; }
     //view
       <label>
            @Html.RadioButtonFor(m => m.SelectedRoleType, "JobSeeker", new { @class = "js-radio", id = "" })
            <span>Job Seeker</span>
        </label>

        <label>
            @Html.RadioButtonFor(m => m.SelectedRoleType, "Referrer", new { @class = "js-radio", id = "" })
            <span>Referrer</span>
        </label>
      //controller action
        [HttpPost]
        public ActionResult Create(CoverLetterViewModel viewModel)
        {//somecode}

尝试3: 现在假设我有10个单选按钮,有什么有效的方法来创建单选按钮吗?我的意思是,假设我有一个单选按钮项目列表,如下所示

public List<SOME RADIBUTTON ITEM> radiobuttonlist {get;set;}

问题:

我们是否可以以与处理下拉项列表相同的方式显示单选按钮。我们是否可以通过某种方式避免在视图文件中硬编码"Referrer""JobSeeker"文本

推荐答案

我们是否可以以与处理下拉项列表相同的方式显示单选按钮。

否,没有内置的HTML Helper来呈现单选按钮列表。

但是,您可以使用简单的Foreach循环并逐个呈现它们。

仅供参考:如果value和key相同,则只需使用List<string>,而不是Dictionary<string, string>

操作方法

public ActionResult Index()
{
    var model = new SampleViewModel
    {
        Items = new Dictionary<string, string> {{"Referrer", "1"}, {"JobSeeker", "2"}}
    };
    return View(model);
}

视图模型

public class SampleViewModel
{
    public Dictionary<string, string> Items { get; set; }

    public string SelectedItem { get; set; }

    public SampleViewModel()
    {
        Items = new Dictionary<string, string>();
    }
}

查看

@foreach (var item in Model.Items)
{
    <label>
        @Html.RadioButtonFor(m => Model.SelectedItem, item.Value, 
            new { @class = "js-radio", id = "" })
        <span>@item.Key</span>
    </label>
}

这篇关于如何在ASP.NET MVC 5中正确显示单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆