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.
nameattribute (see here and here). In the other cases@classescapes the C# reserved "class" keyword.@is not necessary for@idjust useid.nameattribute when using theHtmlHelpermethods unless you want your app to fail. Your implementation makes no sense and will not correctly bind to anything. And if your doing this in a loop, then itsfor (int i = 0; i < Model.Count; i++) { @Html.RadioButtonFor(m => m[i].TickerSymbol, 1) @Html.RadioButtonFor(m => m[i].TickerSymbol, 2) }name). You need to go to the MVC site an work through the tutorials and understand the basics. Your model needs a property to bind to.