0

I'm trying to localize an open source project but I'm stuck with enum strings.

My Enum.cs is;

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Web;


namespace TestSite.Domain.Models

    {
    public enum SortSpan
        {
            /// <summary>
            /// Default value
            /// </summary>
            [Display(Name = "Hepsi")]
            All = 0,

            /// <summary>
            /// Span aralığını 1 saate indirger
            /// </summary>
            [Display(Name = "Saat")]
            Hour,

            /// <summary>
            /// Span aralığını 1 güne indirger
            /// </summary>
            [Display(Name = "Gün")]
            Day,

            /// <summary>
            /// Span aralığını 1 haftaya indirger
            /// </summary>
            [Display(Name = "Hafta")]
            Week,

            /// <summary>
            /// Span aralığını 1 aya indirger
            /// </summary>
            [Display(Name = "Ay")]
            Month,

            /// <summary>
            /// Limits search span to ~90 days
            /// </summary>
            [Display(Name = "Mevsim")]
            Quarter,

            /// <summary>
            /// Limits search span to 1 year
            /// </summary>
            [Display(Name = "Yıl")]
            Year
        }
    }

I give [Display(Name = "...")] for each string on my enum SortSpan. But in view it always sees for the string name not DisplayName.

Here is the view;

   @*Top Sort Span Buttons*@
        @if (Model.Context != null && Model.Sort == TestSite.Domain.Models.SortAlgorithm.Top)
        {
            <div>
                <ul class="tabmenu submenu">
                    @{
                        var spans = new SortSpan[] { SortSpan.Day, SortSpan.Week, SortSpan.Month, SortSpan.Quarter, SortSpan.Year, SortSpan.All };
                        foreach (var span in spans)
                        {
<li class='@(Model.Span.HasValue && Model.Span.Value == span ? "selected" : "disabled")'>
@Html.RouteLink(span.ToString(), Model.Submissions.RouteName, new { sort = (Model.Sort == null ? "" : Model.Sort.ToString().ToLower()), span = span.ToString().ToLower() })
</li>
                        }
                    }
                </ul>
            </div>
        }

And this is the live screenshot; It still shows as Day, Week, Month..

But I want to change them with Gün, Ay, Yıl as you can see [Display(Name = "Gün)]...

Thanks..

UPDATE: FULL CODE OF VIEW (.cshtml)

@using Voat.Domain.Models

@model Voat.Models.ViewModels.SubmissionListViewModel

@{
    ViewBag.Title = Model.Title;
    ViewBag.Description = Model.Description;
    int counter = 0;
}

@section PageHeader {
    @if (Model.IsActualSubverse)
    {
        @Html.Partial("_SubverseStylesheetLink", Model.Context.Name, new ViewDataDictionary())
    }
}

<style type="text/css">
    body > .content .link .rank {
        width: 3.2ex;
    }
</style>

<div id="container">
    @if (Model.IsActualSubverse)
    {
        @Html.Action("SidebarForSelectedSubverse", "Subverses", new { selectedSubverse = Model.Context.Name })
    }
    else if (Model.Context != null && Model.Context.Type == Voat.Domain.Models.DomainType.Set)
    {
        @Html.Action("Sidebar", "Set", new { name = Model.Context.FullName })
    }
    else
    {
        @Html.Partial("~/Views/Shared/Sidebars/_SidebarFrontpage.cshtml")
    }

    <div class="content" role="main">

    @*Top Sort Span Buttons *@
    @if(Model.Context != null && Model.Sort == Voat.Domain.Models.SortAlgorithm.Top)
    {
        <div>
            <ul class="tabmenu submenu">
                @{
                    var spans = new SortSpan[] { SortSpan.Day, SortSpan.Week, SortSpan.Month, SortSpan.Quarter, SortSpan.Year, SortSpan.All };
                    Type type = typeof(SortSpan);
                    foreach (var span in spans)
                    {
                        SortSpan sortSpan = SortSpan.All;                               
                        Type type = typeof(SortSpan);
                        MemberInfo[] memberInfo = type.GetMember(sortSpan.ToString());
                        object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
                        string name = ((DisplayAttribute)attributes[0]).Name;   
                        <li class='@(Model.Span.HasValue && Model.Span.Value == span ? "selected" : "disabled")'>@Html.RouteLink(name, Model.Submissions.RouteName, new { sort = (Model.Sort == null ? "" : Model.Sort.ToString().ToLower()), span = name.ToLower() })</li>
                    }
                }
            </ul>
        </div>
    }

        <div class="sitetable linklisting">
            @if (Model.IsActualSubverse)
            {
                @Html.Action("StickiedSubmission", "Subverses", new { subverseName = Model.Context.Name })
            }
            else if (Model.Context == null || (Model.Context != null && Model.Context.Type != DomainType.Set))
            {
                @Html.Partial("~/Views/Welcome/_FirstTimeVisitorWelcome.cshtml")
                @Html.Action("FeaturedSub", "Home")
                @Html.Action("StickiedSubmission", "Home")
            }

            @if (Model.Submissions.Count <= 0)
            {
                Html.RenderPartial("_DefaultMessage", new ViewDataDictionary() {{"selectedSubverse", Model.Context.Name}});
            }

            @foreach (var submission in Model.Submissions)
            {
                @Html.Partial("~/Views/Shared/Submissions/_Submission.cshtml", submission, new ViewDataDictionary() { { "CssClass", new string[] { counter % 2 == 0 ? "even" : "odd" } } })
                counter++;
            }
        </div>

        @{
            Model.Submissions.RouteData = Request.RequestContext.RouteData.Values;
            if (Model.Sort != null)
            {
                Model.Submissions.RouteData["sort"] = Model.Sort.ToString().ToLower();
            }
            if (Model.Span != null)
            {
                Model.Submissions.RouteData["span"] = Model.Span.ToString().ToLower();
            }
            if (!String.IsNullOrEmpty(Request.QueryString["frontpage"]))
            {
                Model.Submissions.RouteData["frontpage"] = Request.QueryString["frontpage"];
            }
        }
        @Html.DisplayFor(model => Model.Submissions, "IPaginatedList")

        @*<div class="pagination-container">
            <ul>
                @if (Model.Submissions.HasPreviousPage)
                {
                    <li class="btn-whoaverse-paging">
                        @Html.RouteLink("< prev", Model.Submissions.RouteName, new {
                       page = (Model.Submissions.PageIndex - 1),
                       sort = (Model.Sort == null ? "" : Model.Sort.ToString().ToLower()),
                       time = (Model.Span == null ? "" : Model.Span.ToString().ToLower()),
                       frontpage = Request.QueryString["frontpage"]
                   }, new {rel = "prev"})
                    </li>
                }

                @if (Model.Submissions.HasNextPage)
                {
                    <li class="btn-whoaverse-paging">
                        @Html.RouteLink("next >", Model.Submissions.RouteName, new {
                       page = (Model.Submissions.PageIndex + 1),
                       sort = (Model.Sort == null ? "" : Model.Sort.ToString().ToLower()),
                       time = (Model.Span == null ? "" : Model.Span.ToString().ToLower()),
                       frontpage = Request.QueryString["frontpage"]
                   }, new { rel = "next" })
                    </li>
                }
            </ul>
        </div>*@

        @if (!Model.IsActualSubverse)
        {
            <div>
                <a href="/random">rastgele evren getir</a> veya <a href="/randomnsfw">rastgele NSFW evren getir </a>
            </div>
        }
    </div>
</div>
Enes Chufy
  • 63
  • 6
  • take a look at this answer https://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via-mvc-razor-code#13100409 – Béranger Jul 20 '17 at 15:03
  • I tried that too but It didn't work for me I don't know why. Actually, I'm not good at ASP and C#, so this language is kind a foreign to me. But when I tried that solution I've got an error about "description". I think I'm doing something wrong when I'm editing view while trying this solution. – Enes Chufy Jul 20 '17 at 15:06

2 Answers2

1

This works for me.

SortSpan sortSpan = SortSpan.All;                               
Type type = typeof(SortSpan);
MemberInfo[] memberInfo = type.GetMember(sortSpan.ToString());
object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
string name = ((DisplayAttribute)attributes[0]).Name;

I used an answer from this link Getting attributes of Enum's value

[Update] Here is the merged code. It's not tested, just edited with an text editor.

 @*Top Sort Span Buttons *@
    @if(Model.Context != null && Model.Sort == TestSite.Domain.Models.SortAlgorithm.Top)
    {
        < div >
            < ul class="tabmenu submenu">
                @{
                    var spans = new SortSpan[] { SortSpan.Day, SortSpan.Week, SortSpan.Month, SortSpan.Quarter, SortSpan.Year, SortSpan.All };
                    Type type = typeof(SortSpan);
                    foreach (var span in spans)
                    {
                        MemberInfo[] memberInfo = type.GetMember(span.ToString());
                        object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
                        string name = ((DisplayAttribute)attributes[0]).Name;
                        <li class='@(Model.Span.HasValue && Model.Span.Value == span ? "selected" : "disabled")'>@Html.RouteLink(name, Model.Submissions.RouteName, new { sort = (Model.Sort == null ? "" : Model.Sort.ToString().ToLower()), span = name.ToLower() })</li>
                    }
                }
            </ul>
        </div>
    }
Ben
  • 763
  • 1
  • 5
  • 14
  • Seen this before but it doesn't work for me or I can't achieve it :D. Thanks. – Enes Chufy Jul 20 '17 at 15:43
  • Hello again Ben, Im getting errors when I insert the first code on my enums.cs that you have sent. I've bolded the lines contains errors. SortSpan **sortSpan** = SortSpan.All; Type **type** = typeof(SortSpan); MemberInfo[] **memberInfo** = **type**.GetMember(**sortSpan**.ToString()); object[] **attributes** = **memberInfo**[0].GetCustomAttributes(typeof(DisplayAttribute), false); string **name** = ((DisplayAttribute)**attributes**[0]).Name; – Enes Chufy Jul 20 '17 at 16:30
  • Can you post some of the errors? Without it is hard to answer ;) – Ben Jul 20 '17 at 16:34
  • Lol, I don't know where should I add them the first code that you have sent so I added the first codes to enums.cs and replaced the second one with my view code :) Let me post as a answer because I can't add image on comments. – Enes Chufy Jul 20 '17 at 16:50
  • Okay here is the errors: [sortSpan Errors](http://i.imgur.com/eZJuGZp.png). – Enes Chufy Jul 20 '17 at 16:55
  • I'm sorry, but what you did was completely wrong. Please remove the first code from enums.cs and replace the code in the view with my second code and test this. – Ben Jul 20 '17 at 16:58
  • btw: you can't add code to a namespace. To test the first one, you have to add it to a method – Ben Jul 20 '17 at 17:00
  • Aw, okay I understood the logic. I did exactly what you have said, now this error. By the way I worked on original files. So changed "TestSite" to "Voat". [Check this](http://i.imgur.com/PMWs5wo.png) – Enes Chufy Jul 20 '17 at 17:09
  • Please remove the first two lines in the loop. They are not part of my second example. – Ben Jul 20 '17 at 17:13
  • These lines are imports another views to this view. These are must should be stay there. If you need full cshtml of this page im going to update my question right now. Check it in few mins. – Enes Chufy Jul 20 '17 at 17:20
  • You misunderstood me. Remove line 70 and 71 (Line numbers are from the error message). – Ben Jul 20 '17 at 17:22
  • Ah sorry, I've deleted those lines but now get another error and I don't understand what is "MemberInfo" on that code because there isn't any enum which contains MemberInfo on my Enums.cs. Here is the screenshot of the error. [Another Error](http://i.imgur.com/1lhOFID.png) – Enes Chufy Jul 20 '17 at 17:36
  • `MemberInfo` https://msdn.microsoft.com/en-us/library/system.reflection.memberinfo(v=vs.110).aspx – Ben Jul 20 '17 at 17:38
  • You are missing an using to System.Reflection – Ben Jul 20 '17 at 17:43
  • @using System.Reflection – Ben Jul 20 '17 at 17:44
  • Oh, I was using them on Enums forgot to use them on View. It seems worked but now When I clicked any listing button which is "Day(Gün), Month(Ay)... etc) It always select "All" as selected. Is this issue related with `object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false); string name = ((DisplayAttribute)attributes[0]).Name;` ?Because In Enums.cs **All = 0** – Enes Chufy Jul 20 '17 at 17:54
  • No, memberInfo[0] is just the first element of the array. – Ben Jul 20 '17 at 17:56
  • Okay i figured it out why this error appears. Because this changes not changed only listing names it changed links too like "/top?span=mevsim". This link was like this before "/top?span="quarter". Links should be stays as it is. I just need to change listing enums displaynames – Enes Chufy Jul 20 '17 at 17:57
  • Oh you misunderstood me :) I figured it out why when I clicked a
  • button not working properly but I didn't solve it. We changed Enum displayname correctly but our changes triggers the links too. Like /top?span="quarter" to /top?span="mevsim". It should stay as /top?span="quarter". Links are shouldn't change.
  • – Enes Chufy Jul 20 '17 at 18:08
  • span = span.Text.ToLower() instead of span = name.ToLower() – Ben Jul 20 '17 at 18:29
  • When changed like you said: "Compiler Error Message: CS0103: The name 'Text' does not exist in the current context" – Enes Chufy Jul 20 '17 at 18:46
  • Compiler Error Message: CS1061: 'Voat.Domain.Models.SortSpan' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'Voat.Domain.Models.SortSpan' could be found (are you missing a using directive or an assembly reference?) – Enes Chufy Jul 20 '17 at 19:54
  • I've solve it with `span = span.ToString().ToLower()`. Now it works like a charm. :) Thank you for your all help! – Enes Chufy Jul 20 '17 at 23:25