Search code examples
arraysjsonsortingcyrillic

Order by name - cyrillic letters


I have a method which returns street names from a stored procedure, something like so

public List<NameUlici> GetAllNameUlici()
        {
            using (var con = new SqlConnection(ConnectionStringManager.GetConnectionManager()))
            {
                var model = con.Query<NameUlici>("GetNameUlici", commandType: CommandType.StoredProcedure).ToList();
                return model;
            }
        }

This is the stored procedure, it simply returns street names

ALTER PROCEDURE [dbo].[GetNameUlici]
    
AS
    SELECT name,ime_1251
    FROM ULICI_KARPOS
    RETURN

and back to the controller I go

public ActionResult GetAllStreets()
        {
            var result = dataRepo.GetAllNameUlici();
            return Json(result);
        }

Then I populate a dropdown with those values. The values I get are in cyrillic so I am not sure how to order them by name, like A - Z. At the moment, I have something like this

$.getJSON(url, function (streets) {
            $("#streetNameID").append('<option></option>');
            $.each(streets, function (index, value) {
                $("#streetNameID").append('<option value="' + value.ime_1251 + '">' + value.ime_1251 + '</option>');
            });
        });

but the dropdown values are all over the place - unsorted, descending & ascending at the same time. Any suggestions on how to proceed?


Solution

  • It is quite terrible how you are "composing" the <option>. If there is a " or a < inside ime_1251 everything will break...

    $("#streetNameID").append(new Option(value.ime_1251, value.ime_1251));
    

    Still. Your problem seems to be C#-side... and in all your C# code there is something I don't see: an ordering. Considering you are using a Stored Procedure, you could order the data inside the SP:

    SELECT name,ime_1251
    FROM ULICI_KARPOS
    ORDER BY ime_1251
    RETURN
    

    Or you can order the data C#-side:

    var model = con.Query<NameUlici>("GetNameUlici", commandType: CommandType.StoredProcedure)
        .OrderBy(x => x.ime_1251)
        .ToList();