如何使用Html.EditorFor在MVC3中渲染单选按钮?
这是我的模特:
[Required] [Display(Name = "I'm a:")] public bool Sex { get; set; }
我的编辑模板:
@Html.LabelFor(model => model.RegisterModel.Sex) @Html.EditorFor(model => model.RegisterModel.Sex)
但是,这将呈现如下:
我如何为男性和女性渲染一些漂亮的单选按钮? 我的模型必须具有什么数据类型?
编辑:
这是我新的更新代码:
//Model: [Required] [Display(Name = "Soy:")] public Gender Sex { get; set; } } public enum Gender { Male = 1, Female = 2 } //Viewmodel: //EditorTemplate: @model GoldRemate.WebUI.Models.Gender @{ ViewBag.Title = "Gender"; }
当我运行它时,我收到此错误:
传递到字典中的模型项为null,但此字典需要“GoldRemate.WebUI.Models.Gender”类型的非null模型项。
造成这种情况的原因是什么?如何在表单中显示我的枚举值?
像这样创建一个枚举:
public enum Gender { Male = 1, Female = 2 }
我会稍微改变你的模型:
public Gender Sex { get; set; }
然后在你看来你会这样做:
Html.EditorFor(x => x.RegisterModel.Sex);
然后你会在这里有一个EditorTemplate:
~/Views/Shared/EditorTemplates/Gender.cshtml
哪个会有这样的内容:
@model EditorTemplate.Models.Gender // switch to your namespace @Html.LabelFor(x => x, "Male") @if(Model == EditorTemplate.Models.Gender.Male) { @Html.RadioButtonFor(x => x, (int)EditorTemplate.Models.Gender.Male, new { @checked = "checked" }); } else { @Html.RadioButtonFor(x => x, (int)EditorTemplate.Models.Gender.Male); } @Html.LabelFor(x => x, "Female") @if(Model == EditorTemplate.Models.Gender.Female) { @Html.RadioButtonFor(x => x, (int)EditorTemplate.Models.Gender.Female, new { @checked = "checked" }); } else { @Html.RadioButtonFor(x => x, (int)EditorTemplate.Models.Gender.Female); }
所以我在Visual Studio中对此进行了建模,这可以按预期工作。 试试看。