MVC3-单选按钮分组和数据库绑定

时间:2012-01-24 14:33:22

标签: asp.net-mvc-3

如何在MVC3 Razor中使用数据库中的单选按钮选项。每个问题我有4个选项,应该从数据库填充选项,并且应该分组。

 @Html.RadioButtonFor(model => Model.AAAa, 'Y', new { title = "Please check this if AAA has been updated" })
                Yes

这给我硬编码值为是,但文本需要用DB Table填充。

如何将选定的值绑回数据库?一个例子会更有帮助。

谢谢

1 个答案:

答案 0 :(得分:7)

与往常一样,您首先要定义一个视图模型,该模型将代表您将在视图中处理的信息:

public class MyViewModel
{
    public string SelectedValue { get; set; }

    // In your question you seem to be dealing with a title attribute as well
    // If this is the case you could define a custom view model ItemViewModel
    // which will contain the Value, the Text and the Title properties for
    // each radio button because the built-in SelectListItem class that I am using here
    // has only Value and Text properties
    public SelectListItem[] Items { get; set; }
}

然后你写了一个控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // Obviously those will come from your database or something
            Items = new[]
            {
                new SelectListItem { Value = "Y", Text = "Yes" },
                new SelectListItem { Value = "N", Text = "No" },
                new SelectListItem { Value = "D", Text = "Dunno" }
            }
        };
        return View(model);
    }

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

然后是相应的观点:

@model MyViewModel
@using (Html.BeginForm())
{
    for (int i = 0; i < Model.Items.Count; i++)
    {
        @Html.RadioButtonFor(x => x.SelectedValue, Model.Items[i].Value, new { id = "item_" + i })
        @Html.Label("item_" + i, Model.Items[i].Text)
        <br/>
    }
    <button type="submit">OK</button>
}

或者为了使视图不那么混乱,您可以编写一个自定义HTML帮助程序,为您呈现这些单选按钮:

public static class HtmlExtensions
{
    public static IHtmlString RadioButtonListFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TProperty>> expression, 
        IEnumerable<SelectListItem> items
    )
    {
        var sb = new StringBuilder();
        var i = 0;
        foreach (var item in items)
        {
            var id = string.Format("item{0}", i++);
            var radio = htmlHelper.RadioButtonFor(expression, item.Value, new { id = id });
            var label = htmlHelper.Label(id, item.Text);
            sb.AppendFormat("{0}{1}<br/>", radio, label);
        }

        return new HtmlString(sb.ToString());
    }
}

现在您的视图将变为:

@model MyViewModel

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

显然更好看。