How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

前端 未结 14 2163
一向
一向 2021-02-06 21:20

How can i Set RadioButtonFor() as Checked By Default

<%=Html.RadioButtonFor(m => m.Gender,\"Male\")%>

there is way out for (Html.Radio

14条回答
  •  天命终不由人
    2021-02-06 21:52

    I found another option so you can just use @Html.EditorFor() with templates:

    Say I have this enum:

    public enum EmailType { Pdf, Html }
    

    I can put this code in Views/Shared/EditorTemplates/EmailType.cshtml

    @model EmailType
    @{
        var htmlOptions = Model == EmailType.Html ? new { @checked = "checked" } : null;
        var pdfOptions = Model == EmailType.Pdf ? new { @checked = "checked" } : null;
    }
    
    @Html.RadioButtonFor(x => x, EmailType.Html, htmlOptions) @EmailType.Html.ToString()
    @Html.RadioButtonFor(x => x, EmailType.Pdf, pdfOptions) @EmailType.Pdf.ToString()
    

    Now I can simply use this if I want to use it at any time:

    @Html.EditorFor(x => x.EmailType)
    

    It's much more universal this way, and easier to change I feel.

提交回复
热议问题