开发者

Pass 2-dimensional array trough view

I'm trying to print a 2-dimensional array but can't figure it out.开发者_如何学JAVA

My controller uses this code:

        public ActionResult Test(string str)
    {

         DateTimeOffset offset = new DateTimeOffset(DateTime.Now);
        offset = offset.AddHours(-5);

        string[,] weekDays = new string[7,2];

        for (int i = 0; i < 7; i++)
        {
            weekDays[i,0] = String.Format("{0:yyyy-MM-dd:dddd}", offset); //Date
            weekDays[i,1] = String.Format("{0:dddd}", offset); //Text
            offset = offset.AddHours(24);
        }

        weekDays[0,1] = "Today";

        ViewData["weekDays"] = weekDays;

        return View();
    }

Now I wan't to print this array of weekdays as a dropdown-list and i thought this would work:

                <% foreach (var item in (string[,])ViewData["weekDays"]) 
               { %>
                <option value=" <%= item[0] %> "> <%= item[1] %>  </option>
            <% } %>

But that's not the case, this code output just the first char of the string.

So anyone got a suggestion?

Thanks!

/M


Issue here is that foreach on array will return string as an item (and not an array) so item[0] works as indexer over string to return first character. Use for (or while) loop and that should do the trick:

<script runat="server">

    private string[,] viewData;

    protected string[,] Data
    {
        get
        {
            return viewData ?? (viewData = (string[,])ViewData["weekDays"]);
        }
    }

</script>

<% for (var i=0; i< Data.GetUpperBound(0); i++) 
               { %>
                <option value=" <%= Data[i][0] %> "> ...
            <% } %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜