Conversion of Date from .Net to Angularjs - c#

when passing an object which contains a date from C# to AngularJS
the value of the date appears as "/Date(1408482000000)/" and not as a valid date.
my angular code:
$scope.GetLastCompletedAction = function () {
$http.post('Default.aspx/GetLastCompletedAction', {}).success(function (data, status, headers, config) {
$scope.objects = JSON.parse(data.d);
}).error(function (data, status, headers, config) {
$scope.status = status;
console.log(status);
});
}
objects is a list of objects.
every object contains a field named startDate which appears invalid.
thanks,
Nadav

you can use a funcion like this
$scope.formatDate = function (jsonDate)
{
var milli = jsonDate.replace(/\/Date\((-?\d+)\)\//, '$1');
var date = new Date(parseInt(milli));
return date;
}

I had this problem before and it is the Date object in javascript that does not consider that date valid.
If you pass to the Date constructor only the number which is inside /Date(*)/, you will see it will work. It did for me.
Hope I helped :)

Related

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value using ajax in mvc

When I am sending data from ajax to the controller at that time it showing the title error. While when I am check the datetime that also coming right only. It showing the current datetime only. Still showing the same error.
I know that the same questions is already ask but then also their answer is not solving my issue.
Here is my code
This is my ajax code
var currentdate = new Date();
var utc = new Date(currentdate.getTime())
$.ajax({
type: "POST",
url: "/Branch/Save",
data: JSON.stringify({ Branch: txtBranch.val(), Address: txtAddress.val(), ContactName: txtContactName.val(), Contactno: txtContactNo.val(), PinNo: txtPin.val(), RegistrationNo: txtReg.val(), GSTNo: txtGST.val(), EnrollNo: txtEnroll.val(), Description: txtDesc.val(), CreatedDateTime: utc, CreatedUserID: 0, UpdatedUserID: 0, UpdatedDateTime: 1/1/1990 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var row = $("#tblBranch tr:last-child").clone(true);
AppendRow(row, r.BranchID, r.Branch, r.Address, r.ContactName, r.Contactno, r.PinNo, r.RegistrationNo, r.GSTNo, r.EnrollNo, r.Description);
txtBranch.val("");
txtAddress.val("");
txtContactName.val("");
txtContactNo.val("");
txtPin.val("");
txtReg.val("");
txtGST.val("");
txtEnroll.val("");
txtDesc.val("");
},
failure: function () {
alert(txtReg.val());
}
});
});
This is my controller code
[HttpPost]
public JsonResult Save(BranchRegistration branchRegistration)
{
using (BranchContext entities = new BranchContext())
{
entities.branch.Add(branchRegistration);
entities.SaveChanges();
}
return Json(branchRegistration);
}
The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.
You usually get this error when your database column is DateTime (not nullable) and your code is not properly setting the value for those column and trying to save it.
This part of your data object,
UpdatedDateTime: 1/1/1990
will send the payload like
UpdatedDateTime":0.0005025125628140704
Which cannot be converted to a valid DateTime object.
Ideally you should be setting these dates in the server, just before saving
[HttpPost]
public JsonResult Save(BranchRegistration branchRegistration)
{
branchRegistration.CreatedDateTime = DateTime.UtcNow;
branchRegistration.UpdatedDateTime = DateTime.UtcNow;
using (var entities = new BranchContext())
{
entities.branch.Add(branchRegistration);
entities.SaveChanges();
}
return Json(branchRegistration);
}

OData cannot find the controller unless the parameter is sent as int

I have this OData controller that works fine for GET and Patch method. However, there's a custom GET method that I had to create in order for use to load the data from a different server and copy to the new one from where the OData retrieves the data. When the user "Retrieves" new data, it sends the date as a parameter. Since it's a new claim for the date, I couldn't put the date in the $filter, hence the new GET method.
This is what the GET method looks like:
[ODataRoute("Claims({key})")]
[HttpGet]
[EnableQuery(AllowedQueryOptions= System.Web.OData.Query.AllowedQueryOptions.All)]
public HttpResponseMessage ClaimByDate([FromODataUri] int key)
{
System.Diagnostics.Debug.WriteLine(key);
string date = key.ToString();
DateTime claimDate = DateTime.ParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime today = DateTime.Today;
if (!ClaimsExistForToday(today))
{
GenerateClaimsList(today, claimDate);
return Request.CreateResponse(HttpStatusCode.OK);
}
return Request.CreateResponse(HttpStatusCode.NotModified);
}
Here's the angularjs controller
vm.retrieve = function () {
if (vm.selectedDate !== null) {
var day = vm.selectedDate.getDate();
var date = (day + "" + (vm.selectedDate.getMonth() + 1) + "" + (vm.selectedDate.getFullYear()));
ClaimService.getClaimsByDate(date)
.then(function (response) { if (response) activate(); })
vm.clear();
}
}
Here's the angular function that's sending the get request:
function getClaimsByDate(date) { //Angularjs service
return $http.get("odata/Claims(" + date + ")")
.then(function (data) {
return true;
});
}
First Issue:
The OData GET method have to have "int" for the parameter. I tried with string and DateTime, but when I send the data with 'string' as paramenter, it won't find the controller at all unless the data was sent as integer. And if I send the date as UTC, I get an error as potentially dangerous and won't execute.
Second Issue:
Sending date as int, it will find the controller if date is sent as 30112015 in the format ddMMyyyy, but it won't find 1112015 or 01112015. It seems like it's only recognizing the date greater than 10. Other than this, everything else works fine including the regular GET method with [EnableQuery].
I found this SO answer Web API and OData- Pass Multiple Parameters which helped me out. I ended up creating a function with the key as parameter. Then it was only a matter of calling the function from Angular.

Post JSON to Asp.net through AngularJS

I currently am working on a website just for fun using AngularJS and ASP.net, this post is a more generalized question because I'm not wondering exactly how to do this, I'm more or less wondering what the best practices are. Currently I have a method in Angular like this
$scope.submit = function () {
console.log(JSON.stringify($scope.form));
$http.post("/post/new", "'" + JSON.stringify($scope.form) + "'").
success(function (data, status, headers, config) {
console.log("Success")
$location.path("/news");
}).error(function (data, status, headers, config) {
console.log("Error");
});
};
And then my corresponding Asp.net code:
[HttpPost][Route("New")]
public IHttpActionResult New([FromBody] string input)
{
JObject json = JObject.Parse(input);
Post p = new Post { Title = (string)json["title"], content = (string)json["content"] };
db.Posts.Add(p);
db.SaveChanges();
return Ok();
}
However I don't believe this is best practice, because first I'm sending everything in as a string and parsing it, but also because if my Title or Content items have an ' character then the program errors out. I'm wondering what is the best way to do this. I believe another way to do it is to pass in my model as parameters to my method, but I'm wondering if there are also other ways to do this besides that as well. Like I said, this isn't an extremely specific question, I just want to know best practices. (A little bit of code to back up your response would be much appreciated)
Thanks!
You should allow JSON.Net to do the deserialization for you in the pipleline rather than in your method. In addition, just post the object itself rather than building out a json string
$scope.submit = function () {
$http.post("/post/new", $scope.form).
success(function (data, status, headers, config) {
console.log("Success")
$location.path("/news");
}).error(function (data, status, headers, config) {
console.log("Error");
});
};
[HttpPost][Route("New")]
public IHttpActionResult New([FromBody] Post input)
{
db.Posts.Add(input);
db.SaveChanges();
return Ok();
}

Pass kendocalendar date to sql database

Scenario:
I know this is a simple datetime conversion, but i'm new to backend and conversions. So please help: I use mvc with ajax to pass the date from kendocalender to scheduler to save it in database:
Here is my code:
controller.cs
public int insertnote(string model,DateTime kendodate)
{
tblDailyNotes Dnote = new tblDailyNotes();
int noteid = 0;
//note.RealDate=Convert.ToString(
Dnote.Note = model;
Dnote.RealDate = kendodate;
noteid = _scheduler.InsertDailynote(Dnote);
return noteid;
}
index.cshtml
$("#dailynotes").change(function () {
debugger;
alert("Changed");
var dailynotes = $('#dailynotes').val();
var calendar = $("#SchedulerCalendar2").data("kendoCalendar");
var cal = calendar.value(new Date());
alert(cal);
$.ajax({
![enter image description here][1]
type: "POST",
url: window.location.pathname + "Scheduler/insertnote",
data: {model:dailynotes, kendodate: cal }
})
.success(function (result) {
alert("note saved successfully");
});
});
Question:
this is the cal alert
How do I convert this output from kendocalendar to "2013-09-01 13:27:14.480"(yyyy-mm-dd hh-mm-ss.sss) this format using jquery to save it in database through controller function. Please help.
you can convert string to DateTime by DateTime.Parse
take a look at this
I agree with user2675751's solution. However, I would recomend using Datetime.TryParse() as this will not throw an exception and return a bool to indicate success or failure. This point is covered in the link user2675751 has provided. It is generally best not to trust data coming from the client.

Passing complex JSON string to 1 parameter webmethod in c# - desearialize into object (json.net)?

I have been happy serializing with javascript objects into JSON using
JSON.stringify
And sending along to my "static" webmethod in c#/asp.net and sure enought it arrives .. I need the correct number of parameters hence if my json object has "startDate","endDate","reserve" then my webmethod needs these as parameters.
"Basically with my order object that i have, i have a number of parameters on this object so i would need to use the same number on the webmethod - this is a bit messy??" - I will explain
I have a rather complex "Order" object in javascript and wish to serialize it using stringify and send it along to my webmethod but i don't want to specify all the parameters is there a way round this?
I was hoping for something like this on my webmethod
public static bool MakeReservation(object order)
Then in my webmethod i only have 1 parameter BUT i can then desearilize this to a true c# object using JSON.NET. I have tried it like this sending the json across but because there is ONLY 1 parameter on my webmethod its failing.
Basically what i am trying to say if i that i want to continue to use my webmethod but i don't want to have to do specify 15 parameters on the webmethod
I want the JSON - String to arrive into my webmethod and then i can decompose it on the server.
Is this possible?
Here is how i am currently sending my JSON to the server (webmethod) using jquery
var jsonData = JSONNew.stringify(orderObject);
$.ajax({
type: "POST",
url: "MyService.aspx/DoReservation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
success = true;
},
error: function(msg) {
success = false;
},
async: false
});
If you try to submit an object that looks like this:
JSON.stringify({ endDate: new Date(2009, 10, 10), startDate: new Date() });
it will try and map endDate and startDate to corresponding parameters in your webmethod. Since you only want to accept one single method, I suspect you may get away with it by submitting the following:
JSON.stringify({ order: orderObject });
Which it might reasonably try to assign as a value to the 'order' parameter of your webmethod. Failing that, submitting
JSON.stringify({ order: JSON.stringify(orderObject) });
and then deserializing it using JSON.NET should definitely work, but it's uglier, so try the first example first. That's my best shot.
It's possible. I'm not so good at explaining stuff, I'll just show you my example code:
Javascript:
var Order = function(name, orderid, price) {
this.name = name;
this.orderid = orderid;
this.price = price;}
var pagePath = window.location.pathname;
function setOrder() {
var jsOrder = new Order("Smith", 32, 150);
var jsonText = JSON.stringify({ order: jsOrder });
$.ajax({
type: "POST",
url: pagePath + "/SetOrder",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function(response) {
alert("wohoo");
},
error: function(msg) { alert(msg); }
});
}
C# Code behind
public class Order
{
public string name { get; set; }
public int orderid { get; set; }
public int price { get; set; }
}
[WebMethod]
public static void SetOrder(object order)
{
Order ord = GetOrder(order);
Console.WriteLine(ord.name +","+ord.price+","+ord.orderid);
}
public static Order GetOrder(object order)
{
Order ord = new Order();
Dictionary<string,object> tmp = (Dictionary<string,object>) order;
object name = null;
object price = null;
object orderid = null;
tmp.TryGetValue("name", out name);
tmp.TryGetValue("price", out price);
tmp.TryGetValue("orderid", out orderid);
ord.name = name.ToString();
ord.price = (int)price;
ord.orderid = (int) orderid;
return ord;
}
My code isn't that beautiful but I hope you get the meaning of it.
I recently went through this very issue with a complexe JSON object I wanted to deserilize in my controller. The only difference is I was using the .toJSON plugin on the client instead of .stringify.
The easy answer:
public static bool MakeReservation(string orderJSON)
{
var serializer = new JavaScriptSerializer();
var order = serializer.Deserialize<Order>(orderJSON);
}
Now, as a longer term solution we created a custom ActionFilterAttribute to handle these cases. It detects the JSON parameters and handles deserilizing the object and mapping to the action. You may want to look into doing the same.

Categories

Resources