FittyFrank
FittyFrank

Reputation: 134

ASP.NET MVC Razor object HtmlAttributes

I was wondering what the difference is between the following two ways of adding object HtmlAttributes in ASP.NET MVC 5. I am using a RadioButtonFor html helper in a foreach loop, and I was having trouble setting the name attribute for the radio buttons so that I could group them correctly. I have it working now, but I do not understand why the solution I found (solution found here:MVC RadioButtonFor group ) works and why mine does not.

Non-working method:

<td>@Html.RadioButtonFor(m => item.PollRating, 1, new { @name = Html.DisplayFor(m => item.TickerSymbol) }) Below </td>

Working method:

 <td>@Html.RadioButtonFor(m => item.PollRating, 2, new { Name = Html.DisplayFor(m => item.TickerSymbol) }) Flat </td>

The difference is using @name vs Name for the object htmlAttributes. Whenever I've had to assign a class or id while using html helpers I used the @class or @id notation, but it does not work in this scenario for name. When I hover over @name and Name in Visual Studio I see the same popup message which states:

"MvcHtmlString 'a.Name {get;}

Anonymous Types:

'a is new {MvcHtmlString Name}"

I am using Visual Studio 2015, target .NET Framework is 4.5.2, and MVC version is 5.2.3.0.

Upvotes: 2

Views: 2177

Answers (1)

DespeiL
DespeiL

Reputation: 1033

When you use @ in htm it mean that it C# code block or element , and @ in C# is you for special varibles name whene name is the same as as system comand (@ class , @interface, @int and others)

 @// line of c# code
    @{
    //c# code body
    }

Also try to use your button in this way

<td>@Html.RadioButtonFor(m => item.PollRating, 2, new { Name=item.TickerSymbol }) Flat </td>

Upvotes: 1

Related Questions