我有一个视图,其中模型具有项目集合。然后,我有了一个EditorFor模板,该模板负责为用户创建一个下拉列表,以便为集合中的每个项目选择有限数量的值之一:

@model Consultants.Models.ProgramSkill
<tr>
    <td>@Model.Program.Name
    </td>
        <td>@Model.Program.Category
    </td>
    <td>
        @Html.DropDownListFor( model => model.Level, new SelectList(new[] { 0, 1, 2, 3, 4, 5 }, Model.Level))
    </td>
</tr>


但是我宁愿让单选按钮做同样的事情,在MVC 3中有可能吗?如果是这样,怎么办?

最佳答案

那将是自定义html助手的理想选择:

using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text;
using System.Collections.Generic;
using System.Linq.Expressions;
using System;

public static class HtmlExtensions
{
    public static MvcHtmlString RadioButtonListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex, IEnumerable<SelectListItem> values)
    {
        string name = ExpressionHelper.GetExpressionText(ex);
        var sb = new StringBuilder();
        int counter = 1;
        foreach (var item in values)
        {
            sb.Append(htmlHelper.RadioButtonFor(ex, item.Value, new { id = name + counter.ToString()}));
            var label = new TagBuilder("label");
            label.SetInnerText(item.Text);
            label.Attributes.Add("for", name + counter.ToString());
            sb.Append(label.ToString());
            counter++;
        }
        return MvcHtmlString.Create(sb.ToString());
    }
}


模型:

public class MyViewModel
{
    public IEnumerable<SelectListItem> Items { get; set; }
    public string Level { get; set; }
}


控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Level = "2",
            Items = Enumerable.Range(1, 5).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = "item " + x
            })
        };
        return View(model);
    }
}


和一个视图:

@model AppName.Models.MyViewModel

@using (Html.BeginForm())
{
    @Html.RadioButtonListFor(x => x.Level, Model.Items)
    <input type="submit" value="OK" />
}

关于asp.net - 在MVC 3应用程序中使用单选按钮代替dropdownlist吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5435748/

10-11 13:54