我有以下型号: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 => model
到model => model.Gender
),则一切都按预期工作。我知道这是一个可行的解决方法,但这些模板化的助手是如此令人惊叹,令人上瘾的便利,我宁愿在让他们走之前用尽所有可能。
+1和答案。工作过一种享受!这也不是那么丑陋。如果有的话,我宁愿忍受我的'@ Html.EditorForModels()'谢谢!:) –
我同意这不是丑陋的,而且工作的魅力。 – danludwig
我采纳了这个想法并对其进行了扩展。我将一个List>传递给我的编辑器模板,作为添加的ViewData,用于创建单选按钮。我的模板看起来像这样 –
davidbitton