ASP.NET WebApi DateTimeOffset serialize to Json/JavaScript (angular2) - javascript

I do not find a nice way to get a DateTimeOffset value to JavaScript (angular2).
I am using WebApi (5.2.3) and angular2. On the wire I see the date as follow:
RecordModifiedAt : "2016-03-08T17:27:11.9975483+01:00"
JavaScript/angular2 does not recognize this as valid datetime value.
I do have options, but what direction should I go:
Server side: Newtonsoft.Json, ...
Client side: angular2, ...
Others?
Many thankx for your help!

Thankx to PierreDuc feedback I have played around and I came to the following conclusion:
Since JSON does not support a Date datatype, I assume one has to make the conversion on the client side. I use the following 'pattern' (see http://codegur.com/36681078/angular-2-date-deserialization):
getTags() {
return this.http.get('/api/tag/getAll')
.map((response: Response) => this.convertData(response));
}
private convertData(response: Response) {
var data = response.json() || [];
data.forEach((d) => {
// Convert to a Date datatype
d.RecordModifiedAt = new Date(d.RecordModifiedAt);
});
return data;
}

Related

Is there any method to convert string to map<int, dynamic>?

I make an API from Laravel and check the 'Get' request from Postman where it will return as follow:
"answer_selected": "{1:\"True\",2:\"False\"}"
Then, the Flutter application will read the JSON and serialize it using the model class.
Are there any ways to convert the value of "answer_selected" to map<int, dynamic>? Or, my JSON API response format is incorrect?
You should not return a string that is not a complete JSON. Either return
{"answer_selected": {1:"True",2:"False"}}
or
{1:"True",2:"False"}
will be much better. jsonDecode in dart supports decode to map<String, dynamic, and the key in JSON must be string too. So the JSON should like
{"1":"True","2":"False"}
If you want to transform it to map<int, dynamic>, just do
void test() {
String text = '{"1":"True","2":"False"}';
Map<String, dynamic> map = jsonDecode(text);
Map<int, dynamic> desiredMap =
map.map((key, value) => MapEntry(int.parse(key), value));
desiredMap.entries.forEach((element) {
print('${element.key} ${element.value}');
});
}

Handling javascript FormData combined with json data in an XMLHttpRequests post request received by Laravel

I had some form data that I sent as json using XMLHttpRequests. This worked fine, until I needed to add some uploaded file in the post data. I did this by using https://developer.mozilla.org/en-US/docs/Web/API/FormData. However, handling this data in Laravel becomes harder now. I am looking for a better solution for this. Examples:
Sending json only
I used to send something like this:
const otherData = { field1: true, field2: null, field3: [1, 2, 3] };
axios.post('path/somewhere', otherData);
This allows me to read the request data in Laravel as simple as $request->field3.
Sending both json and a file
When a file has to be send as well, I use something like this:
const FormData = new FormData;
formData.append('myFile', someFile);
formData.append('otherData', JSON.stringify(otherData));
axios.post('path/somewhere', formData);
But now in Laravel I cannot easily access my otherData like $request->otherData->field3, since $request->otherData is just a string. I also lose other conveniences such as the TrimStrings middleware, and easy validation like $request->validate(['field3' => 'required']); since field3 doesn't exist anymore in the request.
So I have just solved this as I had exactly that issue - I had my lovely vue component passing JSON back to my Laravel Controller via axios and using a FormRequest to handle validation. Well, you know what happened... so the solution I used.
1) The component in the view.
let data = new FormData()
for (var i=0; i<this.services.length; i++){
data.append('services[]', JSON.stringify(this.services[i]))
}
axios.post('/api/services', data, {headers: {"Content-type": "multipart/form-data"}})
.then((response) => {
2) The Validation
class ServiceRequest extends FormRequest{
public function rules(){
$rules = [
'services.*.name' => 'required|min:1|max:128'
];
return $rules;
}
3) The bit that makes it work; override the function in FormRequest prepareForValidation like so
protected function prepareForValidation()
{
$services = $this->input("services");
$newServices = array();
foreach ($services as $service) {
$service = json_decode($service, true);
$newServices[] = $service;
}
$this->merge([
'services' => $newServices
]);
}
Boom! Validation works just like it did before you had the great idea to add files or images to the submission.
This works because you transform the string that is now my services array, notice in the vue component I have passed my serivces object as an array type "services[]" this was not required before using the FormData and tells PHP to convert the services[] into an array (Unique to PHP I believe). Normally that string would be automatically converted to JSON by laravel but when getting it from the multipart request is it only a string - probably because of the mime type and so need to be converted back into an object before validation, once that is done everything behaves the way it used to.

Accessing .json file to get bank holidays access denied

I am very new to jQuery and json. I am trying to get UK Bank Holiday data from the following API/link so that I can create a function which determines if a selected date is a working day.
https://www.gov.uk/bank-holidays.json
I had an error for No Transport which I fixed by putting in:
jQuery.support.cors = true;
I am now getting Access Denied. I have no idea how to gain access to this because as I say, I am still learning all this.
function IsWorkingDay(date) {
var day = new moment(value, "DD-MM-YYYY").day();
jQuery.support.cors = true;
var bankHolidays = $.getJSON("https://www.gov.uk/bank-holidays.json").done(function(data) {
alert(data);
})
.fail(function(a, b, c) {
alert(b + ',' + c);
return day != 0 && day != 6;
}
});
My question is in two phases:
How do I get access? (Main question)
How do I move on to access the data? I have downloaded the json onto my computer to look at, just how I am going to go about translating this to javascript is what I am struggling on.
If you are blocked by CORS, and the service doesn't support JSONP, the easiest way to solve it is to create a proxy service for the actual service. So if you create a service on your server (which is the same that is serving the javascript), you can call that service, which in turn will fetch the data from the external service. On the server side, there is no CORS to worry about.
I don't know what your backend is, but the steps are as follows:
Create a service on your side that is exposed with a URL (e.g. /myapp/workingday)
Call this service instead of the real service
Your proxy service will get the JSON data and return it to the javascript
Edit
I don't know MVC4, but I suspect it's some of the same concepts as Spring MVC, so here's a Java example:
#Controller
public class HolidaysController {
#RequestMapping("/workingday")
public void isworkingDay(#RequestParam("day") Date day, HttpServletResponse response) {
// Call external service and get JSON
String json = callExternalService(day);
response.setContentType("application/json");
response.getWriter().write(json);
}
}
And in your javascript:
function IsWorkingDay(date) {
var day = new moment(value, "DD-MM-YYYY").day();
var bankHolidays = $.getJSON("/workingday").done(function(data) {
// process data
});
}
For this to work you need to use jsonp as illustrated here
BUT
running the above code throw an invalid label exception which as explained here and as #NilsH suggests is due to the server blocking it

send java script function parameter to ASP.NET MVC helper method

I have a Ajax form in my asp.net mvc application, which has a onSuccess callback as below:
function onSuccessReport(context)
{
$('reportChart').empty();
var line1=#Html.GetStrippedString(context.Expenses);
}
I defined a html helper which accept an string an manipulte it and return a string.
What I pass to onSuccessReport, is a json result which has a structure like this:
But I cant send context.Expenses and the application throws syntax error.
How can I send a javascript variable to my helper?
Thanks
Edited:
The error in my view
****Error 1 The name 'context' does not exist in the current context****
C# method
json = json.Replace("\"Date\":", string.Empty);
json = json.Replace("\"Total\":", string.Empty);
json = json.Replace('}', ']');
json = json.Replace('{', '[');
return MvcHtmlString.Create(json);
You are mixing client side code (javascript) with server side code (HtmlHelper). You cannot pass client side variables to server side helpers. If the context variable is known only on the client then you will have to write a client side javascript function instead of server side helper. So move to logic you wrote in this Html.GetStrippedString helper into a javascript function that you could call from your script.
Actually, you can send javascript values over to the server side if you use Ajax. Instead of using your helper method the way you are, just change it into an action within the Controller to return you some Json (could just be a string, number, object, etc, etc). Here is an example of what you might try out.
View
function onSuccessReport(context)
{
$('reportChart').empty();
var expenses = context.Expenses;
$.getJSON('#Url.Action("GetStrippedString", "ControllerName")', { expenses: expenses }, function (data) {
//pending what you pass back as data, do whatever with it
alert(data);
});
}
Controller
public JsonResult GetStrippedString(string expenses)
{
var result = string.Empty;
//Do something to string
return Json(result, JsonRequestBehavior.AllowGet);
}

OpenRasta CreatedResourceUrl use

I am sending the following response from server :
return new OperationResult.Created { CreatedResourceUrl = getURI(newDuplicateKfEntity), ResponseResource = newDuplicateKfEntity };
My question is how can I get this CreatedResourceUrl object in my javascript??
Instead of OperationResult.Created return a typed DTO and use a Codec to encode it as Json. After that consuming Json in JavaScript is simple.

Categories