如何使用Html.EditorFor在MVC3中渲染单选按钮?

时间:2011-08-17 19:36:05

标签: c# asp.net-mvc-3 model

这是我的模特:

[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" />

当我运行时,我收到此错误:

  

传入字典的模型项为null,但是这个字典   需要类型为非null的模型项   'GoldRemate.WebUI.Models.Gender'。

造成这种情况的原因是什么?如何在表单中显示我的枚举值?

1 个答案:

答案 0 :(得分:20)

像这样创建一个枚举:

 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中对此进行了建模,这可以按预期工作。尝试一下。