Sunday, May 12, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  14] [ 1]  / answers: 1 / hits: 45436  / 15 Years ago, mon, august 3, 2009, 12:00:00

When I parse a DateTime to json in .Net it returns a string (i.e. /Date(1249335194272)/). How do I make it return a js Date object constructor not wrap in a string?



// js server code
var dteNow = <%= jsonDateNow %>;


// js rendered code
var dteNow = /Date(1249335477787)/;


// C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

namespace testing{
public partial class iTaxPrep : System.Web.UI.Page
{
protected string jsonDateNow;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
jsonDateNow = new JavaScriptSerializer().Serialize(DateTime.Now);

}
}
}
}

More From » c#

 Answers
69

This seems to work (Thanks Chris S for the idea). In the C# do a replace to remove the string wrapper from around the date object;



    using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI.WebControls;

namespace test
{
[ScriptService]
public partial class testing: System.Web.UI.Page
{
protected string strCaseID;
protected string jsonCase;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
strCaseID =Tools.GetQueryObject(id);
// get a complex object with dates, string, arrays etc.
jsonESHACase = new JavaScriptSerializer().Serialize(objCase.Get(strCaseID ))
.Replace(\/Date(, new Date().Replace()\/, ));
}
}
}
}


..and after removing the quotes and adding the new prefix to Date this js now works. Hooray!



testCase= <%= jsonESHACase %>;
if (testCase) {
document.write(testCase[ClosingDate].format(MM dd yyyy));
}

[#99000] Thursday, July 30, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
efrainjamiry

Total Points: 234
Total Questions: 110
Total Answers: 112

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
efrainjamiry questions
;