这是我的模型:
[Required]
[Display(Name = "I'm a:")]
public bool Sex { get; set; }
还有我的编辑器模板:
<div>
@Html.LabelFor(model => model.RegisterModel.Sex)
@Html.EditorFor(model => model.RegisterModel.Sex)
</div>
但是这呈现如下:
<div>
<label for="RegisterModel_Sex">Soy:</label>
<input class="check-box" data-val="true" data-val-required="The Soy: field is required." id="RegisterModel_Sex" name="RegisterModel.Sex" type="checkbox" value="true" /><input name="RegisterModel.Sex" type="hidden" value="false" />
</div>
我如何为男性和女性呈现一些漂亮的单选按钮?我的模型必须具有什么数据类型?
编辑:
这是我新更新的代码:
//Model:
[Required]
[Display(Name = "Soy:")]
public Gender Sex { get; set; }
}
public enum Gender
{
Male = 1,
Female = 2
}
//Viewmodel:
<fieldset>
<legend>Informacion Personal</legend>
<div>
@Html.LabelFor(model => model.RegisterModel.Nombre)
@Html.EditorFor(model => model.RegisterModel.Nombre)
</div>
<div>
@Html.LabelFor(model => model.RegisterModel.Apellido)
@Html.EditorFor(model => model.RegisterModel.Apellido)
</div>
<div>
@Html.LabelFor(model => model.RegisterModel.Sex)
@Html.EditorFor(model => model.RegisterModel.Sex)
</div>
<div>
@Html.LabelFor(model => model.RegisterModel.Carnet)
@Html.EditorFor(model => model.RegisterModel.Carnet)
</div>
</fieldset>
//EditorTemplate:
@model GoldRemate.WebUI.Models.Gender
@{
ViewBag.Title = "Gender";
}
<input type="radio" name="Sex" value="@Model" />
当我运行它时,我得到这个错误:
The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'GoldRemate.WebUI.Models.Gender'.
这是什么原因造成的?我该如何在我的表单中显示我的枚举值?
最佳答案
像这样创建一个枚举:
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 中对此进行了建模,并且按预期工作。试试吧。
关于c# - 如何使用 Html.EditorFor 在 MVC3 中呈现单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7098411/