Razor behaving strangely?
Razor is playing tricks with me. I have a partial view:
@model ManageMvc.Models.Default.Classes.MvcModule
@{
if (Model.CanExpand)
{
Response.Write("Crazy");
@:TEST
<text>ojiiojjiojiojiojiojiojiojio</text>
Response.Write("Crazy2");
}
else
{
Response.Write("Crazy");
@:TEST
<text>ssssssssdffffffff</text>
Response.Write("Crazy2");
}
}
This is called from this:
@if (Model.Modules.Count > 0)
{
for (var i = 0; i < Model.Modules.Count; i++)
{
Html.Partial("~/Views/UserControls/_MenuItem.cshtml", Model.Modules[i]);
}
....
}
I expected razor to print out whats written inside the Text block and the @: block. But i get nothing. When i run this it just prints CrazyCrazy2 (for each module in the list). Did i miss something?
Updated
The code that is calling if (Model.Modules.Count > 0) is a partial itself. That one is called from the layout page. So the top code is the second partial being called. Can this make any difference?
Layout -> MainMenu (partial) -> CreateMenuItem (partial)
Updated
This is the new code: (_MenuItem.cshtml inside Shared->DisplayTemplates)
@model ManageMvc.Models.Default.Classes.MvcModule
@{
if (Model.CanExpand)
{
@:TEST
<text>ojiiojjiojiojiojiojiojiojio</text>
}
els开发者_Python百科e
{
@:TEST
<text>ssssssssdffffffff</text>
}
}
Partial view MainMenu that is calling the menu item:
@Html.DisplayFor(x => x.Modules, "_MenuItem")
Now this breaks on that line and i get the following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[ManageMvc.Models.Default.Classes.MvcModule]', but this dictionary requires a model item of type 'ManageMvc.Models.Default.Classes.MvcModule'.
Put an @
when calling the Html.Partial
helper and avoid using Response.Write
in an ASP.NET MVC view:
for (var i = 0; i < Model.Modules.Count; i++)
{
@Html.Partial("~/Views/UserControls/_MenuItem.cshtml", Model.Modules[i]);
}
Also instead of writing some ugly loops I would strongly suggest you using templated helpers. So replace the for loop in your layout with this simple helper:
@Html.DisplayFor(x => x.Modules)
and then define the display template (~/Views/Shared/DisplayTemplates/MvcModule.cshtml
) which will be rendered for each element of the Modules
collection:
@model ManageMvc.Models.Default.Classes.MvcModule
@if (Model.CanExpand)
{
@:TEST
<text>ojiiojjiojiojiojiojiojiojio</text>
}
else
{
@:TEST
<text>ssssssssdffffffff</text>
}
See how easier this is?
精彩评论