3

I'm trying to declare a Html.Radio button in my mvc app and want to output a data- attribute. Problem is c# does like "-"

<%= Html.RadioButton("defaultRadioButton", d.Link, d.IsDefault, new { data-link = d.Link })%>

Is there anyway to get round this other than outputting the html myself or creating a helper?

Thanks..

1 Answer 1

11

If this is ASP.NET MVC 3:

<%= Html.RadioButton(
    "defaultRadioButton", 
    d.Link, 
    d.IsDefault, 
    new { 
        data_link = d.Link 
    }
)%>

and the underscore will be automatically converted into a dash by the helper.

In previous versions of MVC an ugly hack could be appiled:

<%= Html.RadioButton(
    "defaultRadioButton", 
    d.Link, 
    d.IsDefault, 
    new Dictionary<string, object> { 
        { "data-link", d.Link } 
    }
) %>
Sign up to request clarification or add additional context in comments.

4 Comments

Ahh I thought I'd seen it like that somewhere. Unfortunatley we haven't moved to 3 yet. Although we may be doing so soon.
@mjmcloug, OK, see the ugly hack then.
@mjmcloug, a custom HTML helper could save you from the burden of this ugliness. Also wishing you a soon migration to MVC 3.
I'll have to see if how often this crops up before creating a custom helper... No point doing so if this is the only case and we do migrate soon. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.