handling html attributes with dashes with htmhelper in mvc for Invalid anonymous type member declarator
In versions prior to ASP.NET MVC 3, you could not declare HTML attributes with dashes/hyphens, without creating a custom type that handled dashes for you. Most of you, who have used custom data attributes with dashes in MVC 1 and 2, must be familiar with the Compiler Error CS0746:
if you use attribute name e.g "data-name", you will see an error
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access
However in ASP.NET MVC 3, there is a trick that can be used to handle HTML attributes with dashes. Just use ‘underscores’ in your custom data attribute instead of ‘hyphens’. MVC 3 using the HTML helpers, automatically converts these underscores into dashes/hyphens
eg:
@Html.HiddenFor(Model => Model.PartnerId, new { ng_model = "PartnerId" })
when view will be rendered then it'll be convert as shown below.
<input type="hidden" name="PartnerId" value="1", ng-model="PartnerId" />
if you use attribute name e.g "data-name", you will see an error
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access
However in ASP.NET MVC 3, there is a trick that can be used to handle HTML attributes with dashes. Just use ‘underscores’ in your custom data attribute instead of ‘hyphens’. MVC 3 using the HTML helpers, automatically converts these underscores into dashes/hyphens
eg:
@Html.HiddenFor(Model => Model.PartnerId, new { ng_model = "PartnerId" })
when view will be rendered then it'll be convert as shown below.
<input type="hidden" name="PartnerId" value="1", ng-model="PartnerId" />
Comments
Post a Comment