2
votes

With Razor html helpers it seems kind of poorly done to add custom html attributes.

I'm writing payment gateway integration and the card details need to be encrypted on the client's side.

Typical form field looks like

  <input type="text" data-eway-encrypt-name="EWAY_CARDNUMBER" />

I have tried to replicate this with

@Html.TextBoxFor(m => m.Card.CardNumber, new { @class = "form-control", @data-eway-encrypt-name = "EWAY_CARDNUMBER" })

but no luck because it throws back

CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Any Ideas?

2
Can't you do this in JavaScript?Praveen Kumar Purushothaman
there must be a way to add the attribute in razorTobusBoulton

2 Answers

8
votes

You can't have dash in property name. Use underscore instead, they will be automatically converted for you :

@Html.TextBoxFor(
    m => m.Card.CardNumber, new 
    { 
        @class = "form-control", 
        //@data-eway-encrypt-name = "EWAY_CARDNUMBER",
        data_eway_encrypt_name = "EWAY_CARDNUMBER",
    })
1
votes

Use like below:

@Html.TextBoxFor(
    m => m.Card.CardNumber, 
    new { 
        @class = "form-control", 
        data-eway-encrypt-name = "EWAY_CARDNUMBER",
    }
)

The _ will automatically be converted to - in the resulting markup:

<input type="text" data-eway-encrypt-name="EWAY_CARDNUMBER" />