TobusBoulton
TobusBoulton

Reputation: 181

Custom Razor Html Attributes

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?

Upvotes: 1

Views: 2747

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

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" />

Upvotes: 0

Xiaoy312
Xiaoy312

Reputation: 14477

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",
    })

Upvotes: 8

Related Questions