2011-12-02 54 views
5

我有以下型号:RadioButtonFor在编辑模版选择值

public class Person 
{ 
    public string Name { get; set; } 
    public string Gender { get; set; } 
} 

我想默认的性别是女性,所以我设置了在行动:

public ActionResult Create() 
{ 
    var model = new Person { Gender = "F" }; // default is female 
    return View(model); 
} 

最后,视图呈现的一切是这样的:

@model Person 

@using (Html.BeginForm()) 
{ 
    @Html.EditorForModel() 
    <p><input type="submit" value="Create" /></p> 
} 

这一切都按预期工作。现在,让我们说,而不是一个简单的文本框,我想显示性别作为一个更直观的一对单选按钮。所以,我提出以下模板,并将其保存到共享/ EditorTemplates/Gender.cshtml:

@model string 
@Html.RadioButtonFor(model => model, "F") Female 
@Html.RadioButtonFor(model => model, "M") Male 

最后我装点性别与[UIHint("Gender")]

性别现在正确地单选按钮,这是伟大的呈现,但...

问题

女不再是预先选定为默认值,而是我结束了与两个单选按钮空白。我错过了什么吗?

有趣的是,如果我将RadioButtonFor从模板移动到视图(更改model => modelmodel => model.Gender),则一切都按预期工作。我知道这是一个可行的解决方法,但这些模板化的助手是如此令人惊叹,令人上瘾的便利,我宁愿在让他们走之前用尽所有可能。

回答

9

我知道这是丑陋的,但以下可能的工作:

@model string 
@Html.RadioButton("", "F", Model == "F") Female 
@Html.RadioButton("", "M", Model == "M") Male 

与单选助手的问题是,如果第一个参数为空或空,它会永远把它作为非托运从而使这一帮手不合适为编辑器模板。

下面是从MVC源代码的摘录这说明我的意思:

bool isChecked = !string.IsNullOrEmpty(name) && string.Equals(htmlHelper.EvalString(name), b, StringComparison.OrdinalIgnoreCase); 

作为替代,你可以使用一个custom HTML helper产生单选按钮的列表。

+0

+1和答案。工作过一种享受!这也不是那么丑陋。如果有的话,我宁愿忍受我的'@ Html.EditorForModels()'谢谢!:) –

+0

我同意这不是丑陋的,而且工作的魅力。 – danludwig

+0

我采纳了这个想法并对其进行了扩展。我将一个List >传递给我的编辑器模板,作为添加的ViewData,用于创建单选按钮。我的模板看起来像这样 – davidbitton

0

我把这个想法并加以扩展。我将List<Dictionary<string,string>>传递给我的编辑器模板,添加了ViewData用于创建单选按钮。我的模板看起来像这样

@model string 
@{ 
    var buttons = (List<Dictionary<string, string>>)ViewData["Buttons"]; 
} 
@foreach (var button in buttons) { 
    <label class="radio inline"> 
     @Html.RadioButton(Html.NameForModel().ToHtmlString(), Model, Model == button["Value"], new { id = Html.IdForModel() }) @button["Label"] 
    </label> 
} 

这是我通过什么我EditorFor额外ViewData

new { Buttons = new List<Dictionary<string, string>> { new Dictionary<string, string> { { "Label", "Commercial" }, { "Value", "Y" } }, new Dictionary<string, string> { { "Label", "Residential" }, { "Value", "N" } } } } 

授予我这个从我的控制器添加到视图模型类型,并传递到视图但是,在cshtml文件中执行该操作会更快。