3

I have this silly problem, which I hope someone could help me enlighten. I am building an extension for Umbraco7's backoffice, for that I need to receive a simple string. My problem is the string return from the REST api contain double quotes and then AngularJS wont model bind. Here's my API method:

public String GetWeek()
{
        var datetime = DateTime.Now;
        var cultureInfo = new CultureInfo("da-DK");
        var calendar = cultureInfo.Calendar;

        var week = calendar.GetWeekOfYear(datetime, cultureInfo.DateTimeFormat.CalendarWeekRule, cultureInfo.DateTimeFormat.FirstDayOfWeek);
        return datetime.Year + "-W" + week;
}

If someone could explain, how I get rid of these double quotes, I will be really grateful :)

The result:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">"2015-W24"</string>
Filburt
  • 17,626
  • 12
  • 64
  • 115
DNRN
  • 2,397
  • 4
  • 30
  • 48
  • Oh thank for the edit :) – DNRN Jun 12 '15 at 09:03
  • 2
    Since you are using the service from js, why not return json. Just an opinion. (That'll not solve your problem though). How are you creating the REST api? e.g. Web Api doesn't put the quotes. – Arghya C Jun 12 '15 at 10:08
  • I am using Umbraco7's UmbracoApiController. – DNRN Jun 12 '15 at 11:00
  • @ArghyaC I found a way to return json instead, and as you pointed out it solved the problem. Thanks – DNRN Jun 15 '15 at 19:30

2 Answers2

0

Use substring:

var foo = '"2015-W24"';
console.log(foo.substring(1, foo.length - 1)); // 2015-W24
basarat
  • 261,912
  • 58
  • 460
  • 511
0

I found another way than @basarat is suggesting, from the comment form @ArghyaC. The problem is that Umbraco's REST controller builds on asp.net's ControllerApi, and defaults to xml. The apostrophes comes from the xml serialize. The solution is simple force json as the return value instead. I don't dare to change this globally, but can force a method to return with the JsonResult return value:

public JsonResult GetWeek()
    {
        var datetime = DateTime.Now;
        var cultureInfo = new CultureInfo("da-DK");
        var calendar = cultureInfo.Calendar;

        var week = calendar.GetWeekOfYear(datetime, cultureInfo.DateTimeFormat.CalendarWeekRule, cultureInfo.DateTimeFormat.FirstDayOfWeek);
        var weekString = datetime.Year + "-W" + week;

        var result = new JsonResult {Data = weekString};
        return result;
    }

This solves the problem too, but without doing anything in the client.

DNRN
  • 2,397
  • 4
  • 30
  • 48
  • Good that it's resolved. As a side note, I use this in my web api config config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "json", "application/json")); - so for any api call, if you add query string ?format=json, it returns json :) thanks to a great SO answer. Hope you can use something similar. – Arghya C Jun 17 '15 at 04:57