开发者

MVC3 RadioButtonFor - how to set checked="checked" properly

I am trying to achieve html similar to following with MVC开发者_开发技巧3 + Razor:

<input id="x1" type="radio" value="true" name="UseExistingNumberX" checked="checked"/>
<input id="x2" type="radio" value="false" name="UseExistingNumberX"  />

For some reason I cannot get it to work. When I tried following:

@Html.RadioButtonFor(Function(m) m.UseExistingNumber, "true", New With {.id = "r1", .checked = "checked"}) Use Existing Service
@Html.RadioButtonFor(Function(m) m.UseExistingNumber, "false", New With {.id = "r2"}) Add New Service

I get this html output:

<input type="radio" value="true" name="UseExistingNumber" id="r1" data-val-required="The UseExistingNumber field is required." data-val="true" checked="checked"> Use Existing Service
<input type="radio" value="false" name="UseExistingNumber" id="r2" checked="checked"> Add New Service

This is my Model:

Public Class SelectiveServiceStep1Model


    <Required(ErrorMessage:="Postcode is required.")> _
    <RegularExpression("^\d*[0-9]$", ErrorMessage:="Your Postcode must contain only digits.")> _
    Public Property Postcode As String

    Public Property UseExistingNumber As Boolean

End Class

If you notice there are 2 issues with the generated html:

  1. I've only set checked="checked" to "r1" in Razor, but for some reason it also set checked="checked" to "r2". Why?
  2. I haven't marked "UseExistingNumber" in my Model as "Required" field, but why is "r1" rendered with "data-val-required" attribute?

Note: I know that I can write html directly into Razor, and I also know that I can write my own extensions to render the html I want. I just cannot believe that I cannot use the in-built one already, surely I am missing something right?

Thanks


  1. You get the checked attribute because the value of the model is true.
  2. The required flag is being applied because the non-billable bool implies it is mandatory.

When I've done this in the past, I've used HTML.RadioButton instead of RadioButtonFor. note that "field" is whatever you're field is. I would normally put this in an editor template.

       

               
  •                 @Html.RadioButton("field", "True", new { id = (ViewData.TemplateInfo.GetFullHtmlFieldId("field") + "Yes")})                                     Yes                            
  •            
  •                 @Html.RadioButton("field", "False", new { id = (ViewData.TemplateInfo.GetFullHtmlFieldId("field") + "No")})                                     No                            
  •        
        @Html.ValidationMessage("")    

 

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜