How do I use Html.EditorFor to render radio buttons in MVC3?

前端 未结 1 825
再見小時候
再見小時候 2020-12-14 23:46

Here\'s my model:

[Required]
[Display(Name = "I\'m a:")]
public bool Sex { get; set; }

And my editor template:



        
相关标签:
1条回答
  • 2020-12-15 00:34

    Create an enum like so:

     public enum Gender
     {
         Male = 1,
         Female = 2
     }
    

    I'd alter your model slightly like so:

     public Gender Sex { get; set; }
    

    And then in your view you would do this:

     Html.EditorFor(x => x.RegisterModel.Sex);
    

    Then you would have an EditorTemplate here:

     ~/Views/Shared/EditorTemplates/Gender.cshtml
    

    Which would have content like so:

    @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);
    }
    

    So I modeled this in Visual Studio, and this works as expected. Try it out.

    0 讨论(0)
提交回复
热议问题