Reputation: 165
So, I've been using MVC 3, Razor 1, and Web.Helpers 1 now for over a year, but recently moved to MVC 4, Razor 2, and Web.Helpers 2. I've noticed some strange things happening with any View that has inline code or web helpers within an HTML attribute. Namely, the code renders outside of the attribute.
Example 1 : (MVC 3, Razor 1, Web.Helpers 1)
<li class="@{ Write(0 == RowCount % 2 ? "even" : "odd"); }">
Would render as :
<li class="even">
or
<li class="odd">
Example 2 : (MVC 3, Razor 1, Web.Helpers 1)
<img alt="@item.PlanNumber" title="@item.PlanNumber" src="@{Html.RenderAction("GetHomeImage", new { street = (string)item.AddrStreet, photo = (string)item.ELEV1, type = (string)item.RecordType, plan = (string)item.PlanNumber, elevation = (string)item.PlanElevation, defaultImage = (string)item.HomeImage });}" border="0" style="padding:2px 2px 2px 2px;" />
Would render as :
<img alt="2473W" title="2473W" src="/Content/_gallery/homes/photos/17411WOODFALLSLANE_S.jpg" border="0" style="padding:2px 2px 2px 2px;" />
When I updated the site to MVC 4, Razor 2, Web.Helpers 2 I see the following
Example 1 renders as :
<lieven class="">
or
<liodd class="">
Example 2 renders as :
<img alt="2473W" title="2473W" /Content/_gallery/homes/photos/17411WOODFALLSLANE_S.jpg src="" border="0" style="padding:2px 2px 2px 2px;" />
I've been able to work around this by changing the HTML.RenderAction to HTML.Action so my code is now : (MVC 4, Razor 2, Web.Helpers 2)
Example 1:
string rowClass = (0 == RowCount % 2) ? "even" : "odd";
<li class="@rowClass">
Example 2:
<img src="@Html.Action("GetHomeImage", "FindYourHome", new { street = (string)item.AddrStreet, photo = (string)item.ELEV1, type = (string)item.RecordType, plan = (string)item.PlanNumber, elevation = (string)item.PlanElevation, defaultImage = (string)item.HomeImage })" border="0" style="padding:2px 2px 2px 2px;" alt="@item.PlanNumber" title="@item.PlanNumber" />
which renders both examples correctly, but I'm unsure as to why?
I would very much appreciate any information available which will help me find any other instances in our site, and make me feel a lot better about updating to MVC 4, Razor 2 and Web.Helpers 2.
Upvotes: 2
Views: 3150
Reputation: 548
In response as to "why" the new @(....)
syntax works, note that MVC4 included support for "conditional attributes.
See more info here: http://www.davidhayden.me/blog/conditional-attributes-in-razor-view-engine-and-asp.net-mvc-4
Upvotes: 1
Reputation: 947
Can't test it right now but try this :
<li class="@(0 == RowCount % 2 ? "even" : "odd")">
Notice the parenthesis instead of the braces.
Upvotes: 3