user
user

Reputation: 833

Add property with - in name

In MVc I am using Html.TextboxFor() control

I have input type control as below.

<input id="phoneNumber" type="text" class="phoneNumber form-control" value="@actorPhone.PhoneNumber" data-phoneType ="@actorPhone.PhoneTypeTd" data-actorId ="@Model.ActorId" maxlength="30"/>

I want to change this intput control to MVC

@Html.TextBoxFor(m=>m.phoneNumber,new {@class = "phoneNumber", maxlength = "30"})

How I can add data-phoneType and data-actorId properties to the html control, as - is not allowed in the properties of HTML Attribute.

Upvotes: 0

Views: 58

Answers (3)

Mohammed Swillam
Mohammed Swillam

Reputation: 9242

use an underscore _

the Razor engine is smart enough to render the underscore within the property name to the corresponding dash sign, resulting in your desired HTML5-like attributes

example:

    @Html.TextBoxFor(m=>m.phoneNumber,
    new {@class = "phoneNumber", maxlength = "30", 
    data_phoneType = YOUR_VALUE_HERE,    
    data-actorId=YOUR_VALUE_HERE })

and this should result in your desired output.

hope this helps :)

Upvotes: 1

Satpal
Satpal

Reputation: 133453

Use data_* attributes like

@Html.TextBoxFor(m=>m.phoneNumber,
    new {
        data_phoneType=actorPhone.PhoneTypeTd, 
        @class = "phoneNumber", 
        maxlength = "30"
        })

Upvotes: 1

Andrei V
Andrei V

Reputation: 7508

You can set an underscore instead and Razor will render it like a minus/dash:

@Html.TextBoxFor(m => m.phoneNumber, 
      new { data_phoneType = "phone type",  
            @class = "phoneNumber", 
            maxlength = "30"})

Upvotes: 1

Related Questions