Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>OK, now that you have shown your code it is clear why it doesn't work. You use <code>ViewBag</code> (<em>the root of all evil in ASP.NET MVC and the origin of all problems that people are having</em> - little addition from the author of this answer).</p> <p>Once you borrow its path the fall to the abyss is eminent. This fall will be accelerated by the cast that you need to perform in order to make it work:</p> <pre><code>@((int)(ViewBag.Month).MonthToString()) </code></pre> <p>Simply try running the following console application and you will understand that dynamic variables cannot be used to dispatch extension methods:</p> <pre><code>public static class Extensions { public static string MonthToString(this int value) { return (value &gt;= 1 &amp;&amp; value &lt;= 12) ? CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(value) : ""; } } class Program { static void Main() { dynamic foo = 123; Console.WriteLine(foo.MonthToString()); // crash at runtime } } </code></pre> <p>See why I always critique <code>ViewBag</code> when I see people using it? Because it leads you to all kind of strange things. You lose Intellisense, you cannot dispatch extension methods on dynamic variables, ...</p> <p>So actually you don't need to cast. You shouldn't use any ViewBag/ViewData at all. You should be using strongly typed view models:</p> <pre><code>@using BitvaerkAdmin.Models @model MyViewModel &lt;h3&gt; @Model.Month.MonthToString() &lt;/h3&gt; @foreach (Order order in Model.Orders) { &lt;td&gt; @order.Valid.ToYesNo() &lt;/td&gt; } </code></pre> <p>and to avoid the foreach loop you could use display templates:</p> <pre><code>@using BitvaerkAdmin.Models @model MyViewModel &lt;h3&gt; @Model.Month.MonthToString() &lt;/h3&gt; @Html.DisplayFor(x =&gt; x.Orders) </code></pre> <p>and then define a display template for the order which will automatically be rendered by the framework for all elements of the collection (<code>~/Views/Shared/DisplayTemplates/Order.cshtml</code>):</p> <pre><code>@using BitvaerkAdmin.Models @model Order &lt;td&gt; @Model.Valid.ToYesNo() &lt;/td&gt; </code></pre> <p>Everything is now strongly typed and working.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload