Retrieve JSON in MVC [closed] - asp.net-mvc

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have an EntityFramework query in C # in an MVC, the problem is that the result of my code returns undefined, the code in C #:
public ActionResult ListarProductos()
{
sistemaEntities context = new sistemaEntities();
var lista = (from p in context.productos
select p).Where(p => p.nombre_producto.Contains(""));
return Json(new { success = true, message = lista }); // RETURN UNDEFINED
//return Json(new { success = true, message = "hola" }); // RETURN VALID OBJECT
}
The code in Ajax:
app.factory("AppService", function() {
return {
listProductos: function() {
var idata;
$.ajax({
type: 'POST',
url: "/CRUD/ListarProductos",
data: {},
dataType: 'json',
async: false,
success: function(result){idata = result;}
});
alert(idata);
return idata;
}, .. more code
The result in Ajax is "undefined" and I can not find a solution, the result in Ajax I then use it in AngularJS to display a table.
Not a duplicate, the second line of the code in c# works fine in ajax, the problem is the list in entity framework
The test line is commented out and returns a valid object
How can i fix this ?

Based on comment - return Json(new { success = true, message = new List<productos>() }); works.
It might be that productos object has circular references.
You can disable ProxyCreationEnabled, and try again.
context.Configuration.ProxyCreationEnabled = false;
Or return anonymous object with just properties that you need.
var lista = (from p in context.productos
where p.nombre_producto.Contains("")
select new { nombre_producto = p.nombre_producto }).ToList();

Please, try to change the line:
var lista = (from p in context.productos
select p).Where(p => p.nombre_producto.Contains(""));
to:
var lista = (from p in context.productos
select p).Where(p => p.nombre_producto.Contains("")).ToList();
I assume that "lista" is an list of EF proxy classes and the JSON serializer cannot serialize it.

Related

How to make angular2 custom validators to run after we get the value

If I pass hard coded values in offerCheck validator it is working fine. But if I get values from api, null values is getting passed in paramets. Form is getting executed before we get the values from service. Please help me to make validate check after getting values from api.
this.newOffer = "aaa";
this.oldOffer = "aaa";
constructor(fb: FormBuilder) {
this.formGroup = fb.group({
'offer': [null, Validators.compose([Validators.required, this.offerCheck(newOfer, oldOffer)])],
})
offerCheck(new, old) {
return (control: FormControl) => {
if (new == old) {
return true;
}
}
}
What you want is probably the AsyncValidatorFn, here's a very simple example of how to create one:
export const OfferCheck: AsyncValidatorFn = (control: AbstractControl): Observable<boolean> => {
if (new == old) {
return Observable.of(this.http.get('/some-endpoint').first().map(res => res.data));
}
};
You don't provide enough information so this is just a guess on how you'd want it to be. But it should point you in the right decision.
An alternative method would be to use setValidators of the control(s) after you've fetched the data:
this.formGroup.get('offer').setValidators([Validators.required, this.offerCheck(newOfer, oldOffer)]);
I hope this helps.

Get generated ID after insert in UI5 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
My problem is, that I need to get the generated ID of a created entry.
I want to create one entry in my ODataModel and then another one. The second one should hold the ID of the first one as property.
But when I insert the first entry with {"Id" : "0"}, so the ID gets automatically generated, I find no way to get the response Header to save the generated ID in a variable.
I tried to save the response out of the success callback, but the variable stays undefined because of the asynchronicity.
Meanwhile I solved the problem by myself.
I moved the creation of the second entry into the success callback of the first entry.
Thus I was able to get the ID out of the "response" parameter and added it as property to my second entry.
That is probably not the best solution but it works for me.
Maybe somebody else has another proposal to do it better.
This is just a samplecode, but maybe it will help some people who got a similar problem.
// oView = this.getView();
// First Entry for EntitySampleSet1
var oEntry = {};
oEntry.Id = "0";
oEntry.Label = oView.byId("label").getValue();
oEntry.Status = oView.byId("status").getValue();
// Success Callback for the first Entry Creation
// response contains the Response Header for the POST Request
var fnSuccessCallback = function(oData, response)
{
console.log("Success 1");
// Success Callback for the second create methode
var fnSuccess2Callback = function()
{
console.log("Success 2");
};
// Error Callback for the second create methode
var fnError2Callback = function()
{
console.log("Error 2");
};
// Second Entry for EntitySampleSet2
var o2Entry = {};
// ID = "0" so the ID gets automatically generated by JPA
o2Entry.Id = "0";
o2Entry.SampleRelatedObject = response.data.Id;
// The second Entry gets created in the OData Model
oModel.create("/SampleEntitySet2", o2Entry,
{
urlParameters : null,
success : fnSuccess2Callback,
error : fnError2Callback
});
};
var fnErrorCallback = function(oError)
{
console.log("Error1");
};
// The first Entry gets created in the OData Model
// after the create worked fine the fnSuccessCallback will get
// called and the second entry will be created in that method
oModel.create("/SampleEntitySet1", oEntry,
{
urlParameters : null,
success : fnSuccessCallback,
error : fnErrorCallback
});

Caching in Ember with DS.ActiveModelAdapter [duplicate]

I would like to cache my records once they are received, but I can't figure out how. According to the Documentation you can just call this.store.push('model', record), but it doesn't seem to work. Ember requests the data from the server with each call of the route, I would like to do this only once and use the local store after it is fetched from the server.
If I try to debug it as suggested by the Documentation, i get that there is no cache:
Pd.__container__.lookup('store:main').recordCache
// --> undefined
This is my route (where I try to cache it):
Pd.ProductsRoute = Ember.Route.extend({
model: function () {
var promise = this.store.find('product');
var that = this;
promise.then(function(value) {
// Caching supposed to happen here
value.content.forEach(function(product){
that.store.push('product', product);
});
}, function(reason) {
// on rejection
});
return promise;
}
});
And this the according Adapter (seems to work fine):
Pd.ProductAdapter = DS.RESTAdapter.extend({
primaryKey: 'nid', // DOES NOT WORK BUT I CAN LIVE WITH THAT (SEE WORKAROUND)
findAll: function(store, type) {
var url = 'ws/rest/products';
return new Ember.RSVP.Promise(function(resolve, reject) {
jQuery.getJSON(url).then(function(data) {
Ember.Logger.debug("Received Products:"); // TRIGGERS EVERY TIME!
var srcPattern = /src=["']([^'"]+)/;
data.forEach(function(product){
product.id = product.nid;
product.field_image = srcPattern.exec(product.field_image)[1];
});
Ember.Logger.debug(data);
Ember.run(null, resolve, {product: data});
}, function(jqXHR) {
jqXHR.then = null; // tame jQuery's ill mannered promises
Ember.run(null, reject, jqXHR);
});
});
}
});
this.store.find('type') will always make a call to the server for records. If you only want to make a call to the server once do it in the ApplicationRoute and then instead of using find use the all filter inside of the route that's hit multiple times.
Pd.ApplicationRoute = Em.Route.extend({
model: function(params){
return Em.RSVP.hash({
product: this.store.find('product'),
somethingElse: otherPromise
})
}
});
Pd.ProductRoute = Em.Route.extend({
model: function(params){
return this.store.all('product');
}
});
If you just want to prep the store with your products, you don't even need to return it, or use it in the app route
Pd.ApplicationRoute = Em.Route.extend({
model: function(params){
this.store.find('product');
return {foo:'bar'}; // or return nothing, it doesn't matter
}
});
Lazy loading the models
App.ProductRoute = Ember.Route.extend({
hasPreLoaded: false,
model: function() {
if(this.get('hasPreLoaded')){
return this.store.all('product');
} else {
this.toggleProperty('hasPreLoaded');
return this.store.find('product');
}
}
});
Example
http://emberjs.jsbin.com/OxIDiVU/482/edit
You don't define the primary key on the adapter, it goes on the serializer
Pd.ProductSerializer = DS.RESTSerializer.extend({
primaryKey: 'nid'
});
The cache no longer lives there, it lives in this.store.typeMapFor(Pd.Product) or this.store.typeMaps.
The site is still referencing an older version of ember data until ember data 1.0 is released, I'll assume you're using 1.0 beta version. This document is more up to date https://github.com/emberjs/data/blob/master/TRANSITION.md

SignalR and Kendo Ui Scheduler

I'm working in an implementation using SignalR and the Kendo Scheduler. When a new task is created (for exemple), the SchedulerDataSource transport send the connection hub id to the server as an additional parameter:
transport: {
read: { url: global.web_path + 'Home/Tasks' },
update: { url: global.web_path + 'Home/UpdateTask', type: 'PUT', contentType: 'application/json' },
create: { url: global.web_path + 'Home/CreateTask', type: 'POST', contentType: 'application/json' },
destroy: { url: global.web_path + 'Home/DeleteTask', type: 'DELETE', contentType: 'application/json' },
parameterMap: function (options, operation) {
if (operation == "destroy" && options.models) {
return JSON.stringify({ taskId: options.models[0].Id, callerId: $.connection.hub.id });
}
if (operation !== "read" && options.models) {
return JSON.stringify({ tasks: options.models, callerId: $.connection.hub.id });
}
}
},
The server do whatever it has to do, and send a notification to every other user, except de caller:
[HttpPost]
public JsonResult CreateTask(List<ScheduledEvent> tasks, string callerId)
{
...create task and other stuff
//broadcast the newly created object to everyone except caller
var hubContext = GlobalHost.ConnectionManager.GetHubContext<Notebooks.Hubs.SchedulerHub>();
hubContext.Clients.AllExcept(callerId).UpdateSchedule(task);
//return the object to caller
return Json(task);
}
Once the other clients receive a new task from the hub, it is added to the SchedulerDataSource:
hub.client.updateSchedule = function (scheduledEvent) {
schedulerDataSource.add(scheduledEvent);
}
Everything seems to work fine, and it really took me some time to realize this behavior: if a client have the scheduler window open, this window is closed once the schedulerDataSource is updated. This is expected or am I doing something wrong?
Edit: I just realized how old this question is, so you have probably moved on to other things by now, or the pushCreate method may not have existed back then.
I think this may be how it works, but it seems like it should be able to add those events behind the scenes without having to close the edit window. Have you tried the pushCreate method? If that doesn't work, since the add automatically closes the edit dialog, maybe when the events come in, if the dialog is open, you could store the new events, then add them when the user closes the edit dialog.
My answer is now even older ;) but I faced this very same issue today.
First, I'm quite sure this is indeed the expected behavior. You can see in the kendo sources the call of the close editor window method in the transport update and create methods of the scheduler.
Below is what I've done to bypass the issue .
The idea is as simple as to prevent the edit window to close when an appointment modification comes from another hub client.
Server-side : modify the hub methods (example with update method)
public MyAppointmentViewModel Update(MyAppointmentViewModel appointment)
{
if (!appointmentService.Update(appointment))
throw new InvalidOperationException("Something went wrong");
else
{
Clients.Others.PrepareBeforeAddOrUpdateSignal(appointment.Id);
Clients.Others.Update(appointment);
return appointment;
}
}
Here you see we inform every other clients (through PrepareBeforeAddOrUpdate) we're about to update an appintment.
Client-side now (in index.cshtml for instance)
schedulerHub.client.prepareBeforeAddOrUpdateSignal = function(id){ lastModifiedRdvId = id; };
schedulerHub.client.create = function(appointment){ lastModifiedRdvId = 0; }; /* reset the variable for next time */
schedulerHub.client.update = function(appointment){ lastModifiedRdvId = 0; }; /* reset the variable for next time */
function SchedulerEditor()
{
return $(".k-scheduler-edit-form").data("kendoWindow");
}
var eventBeforeChanges = null;
var lastModifiedRdvId = 0;
function onEditorClose(e) {
if (eventBeforeChanges != null) {
if (lastModifiedRdvId > 0 && eventBeforeChanges.Id != lastModifiedRdvId)
e.preventDefault();
else {
var editWin = SchedulerEditor(); /* unbind this callback and use default behavior again */
editWin.unbind('close', onEditorClose);
}
}}
function onEditRdv(e) {
var editWin = SchedulerEditor();
if (editWin != null) /*Bind the close event */
editWin.unbind('close', onEditorClose).bind('close', onEditorClose);
eventBeforeChanges = e.event;
/* continue onEditRdv */
}
you see here the close event is prevented when the appointment id is not the appointment id beeing updated by the current client.
And fortunately, preventing the close event prevents the annoying behavior of having a sort of ghost appointment after one has been changed by another hub client.
I'm sorry if I'm not clear or if the code isn't clear enough. I can provide more information if necessary.
Bye

Trouble Creating JSON with MVC3 (asp.net) using static Json class (system.web.helpers.json)

I'm having trouble creating the following JSON using uisng the C# MVC3 system.web.helpers.json namespace. Here is what I am trying to form:
{"success":true,"msg":"", "Data": [ { "Id":167 } ] }
What I have tried is this (with no success)
var x = Json(
new {Id = result.SponsorListId});
return Json(new
{
success,
msg = success ? "" : "sponsorListResult Passed Into Update as null",
Data = new List<Json>() {x}
}, JsonRequestBehavior.DenyGet);
I've tried lots of other things also, but no point in listing all my failures.
Thanks for any help on this.
Basically all the Json() method does is serialize the object you send it. When you send it a List you are sending it a JsonResponse which isn't what you are intending. What you should do is:
return Json(new
{
success,
msg = success ? "" : "sponsorListResult Passed Into Update as null",
Data = new []{ new { Id: result.SponsorListId } }
}, JsonRequestBehavior.DenyGet);
Which should serialize out to where you want it to be.

Resources