如何在asp.net mvc 5中正确显示radiobutton

时间:2017-08-24 21:19:02

标签: c# asp.net-mvc razor checkbox 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个radiobutton,是否有任何有效的方法来创建radiobutton。我的意思是假设我有一个radiobuttonitem列表,如下所示

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

问题:

我们可以以某种方式显示radiobuttonsame我们处理下拉项目列表的方式。我们能否以某种方式避免在视图文件中对"Referrer""JobSeeker"文字进行硬编码。

1 个答案:

答案 0 :(得分:1)

  

我们可以以某种方式显示radiobuttonsame我们处理下拉列表项目的方式。

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

但是,您可以使用简单的 foreach 循环并逐个渲染它们。

仅供参考:如果价值和关键字相同,您可以使用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>
}