w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
MVC controller not returning JSON data?
You're missing the id? $.getJSON( "/SlimProductServices/JsonDetailsProduct", { 'id': 1 },... public ActionResult JsonDetailsProduct(int id) Take a look at getJson in the jquery docs. Where are you getting the ID from? If you just want to test the call without changing your jquery call, you could add a second Action method... public ActionResult JsonDetailsProduct() { Product pdt = NWDC.GetProduct(1); //hard code product Id that exists for testing.

Categories : Jquery

"Object reference not set to an instance of an object" when creating a new Web API controller with EF Scaffolding in Visual Studio 2012
Found the problem. In my model, I had a property with a custom enum type, which was in my business project. In my service project, I had my data model project referenced but not the business project. So adding a reference to the model AND business project allowed me to add scaffold controllers fine. Seems obvious I know, but the error message it gives you is so unhelpful! Anyway, I hope this helps anyone having the same problem, and can't fix it using the other suggestions.

Categories : Entity Framework

Creating new object in python is not returning a new object
You have created x as a class variable rather than an instance variable. To associate the variable with a particular instance of a class, do something like this: class myObject(object): def __init__(self): # The "constructor" self.x = [] # Assign x to this particular instance of myObject >>> debug: [] >>> debug: [] For a little better explanation of what's going on, have a look at this little mockup that demonstrates the same thing, a little more explicitly (if also more verbosely). class A(object): class_var = [] # make a list attached to the A *class* def __init__(self): self.instance_var = [] # make a list attached to any *instance* of A print 'class var:', A.class_var # prints [] # print 'instance var:', A.instance_var # This would ra

Categories : Python

Error returning JSON formed in yii controller in android
<!DOCTYPE indicates that your service is NOT outputting pure json. It's probably gotten wrapped in an html wrapper, e.g. you've actually got <!DOCTYPE ...> <html> <body> ...json goes here... </body> </html> in other words, your controller is trying to spit out a full-blown HTML page, not just the json response that should be getting output.

Categories : Android

angularjs: returning json data from service to controller
Sure. Try this code function init(){ customersService.getCustomers().then(function(response){ $scope.customers = response.data; }); } this.getCustomers = function() { var promise = $http({ method : 'POST', url : '/CustomerManagementApp/customers/all' }).success(function(data, status, headers, config) { $log.log('Done'); angular.forEach(data, function(c) { $log.log(c.firstName); }); customers = data; return customers; }); return promise; }; promise - as an interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.

Categories : Angularjs

Returning viewmodel from view gives an ampty object in the controller
With the way you construct your view, the ModelBinder cannot differantiate between the different elements in the list, and doesn't recognize them as items in the list. Try constructing the view like this: @{ int datumteller = 0; } @foreach (var item in @Model.Datums) { <tr> <td>@Html.DisplayFor(modelItem => @Model.Datums[datumteller].Dag.Dag.Day)/@Html.DisplayFor(modelItem => @Model.Datums[datumteller].Dag.Dag.Month)/@Html.DisplayFor(modelItem => @Model.Datums[datumteller].Dag.Dag.Year)</td> <td>@Html.EditorFor(modelItem => @Model.Datums[datumteller].Checked)</td> </tr> datumteller++; } @{ int toekomstteller = 0; } @foreach (var item in @Model.Toekomst) { <tr> <td>

Categories : C#

Creating json object from POJO object in restful web service
You can use GSon to convert json object to java object Link to refer example. Gson gson = new Gson(); //to get json object use toJson String json = gson.toJson(obj); //to get java object use fromJson MyClass obj = gson.fromJson(jsonObj, MyClass.class); or jackson is also pretty fast and easy to use

Categories : Java

Creating a method returning a boolean taking an object as argument
you have to override .equals() method based on speed then only you can compare your objects meaningfully. otherwise by default .equals() uses == to compare objects in this case objects can be equal only if they are same

Categories : Java

Returning object oriented json from sparql queries
The JSON output for SPARQL is documented in SPARQL 1.1 Query Results JSON Format, and specifically section 3.2.2 Encoding RDF Terms describes how the RDF is encoded in the JSON. Note that the JSON output is really just for encoding the results of a SPARQL query, not for creating JSON objects that correspond to a particular object model. Your best bet is probably to take the results you're getting and manipulate them yourself. There are still a few things that might be helpful from the SPARQL side, though. group_concat for combining values That said, maybe the following can help you get something that will work a bit better for you. If you have data like this: @prefix : <http://example.org/> . :object :hasA1 :b1, :b2, :b3, :b4 ; :hasA2 :b5 . and a query like this:

Categories : Json

Can a json object's value and key be set in controller action in MVC?
When you're iterating on the jsonObj it should be like this //the first parameter is just the index of the iteration //and the second one is the json object (SelectListItem) $.each(jsonObj, function (index, obj) { $('#aa').append($("<option/>", { value: obj.Value, text: obj.Text })); });

Categories : C#

Creating a json object using jackson
You can write an object to a json string. So I hope you have your data in an object of a class defined as per your need. Here is how you can convert that object into a json string: //1. Convert Java object to JSON format ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writeValueAsString(yourObject); See here for the full jackson-databind javadoc.

Categories : Java

creating an object in json format
You can build your object like this: var availability = {"someTshirt": { 'small': 'available', 'med' : 'available', 'large' : 'not available' } }; Then you can access this object with: availability.someTshirt.small >>> 'available' availability.someTshirt.large >>> 'not available' However I'd recommend you to use booleans instead of strings, which are easier to manipulate. You can still change the display string later: var availability = {"someTshirt": { 'small': true, 'med' : true, 'large' : false } }; if (availability.someTshirt.small) { console.log('available'); } >>> 'available' [edit] Response to the comment: If you want to create your objects dynamically, you can do the followin

Categories : Javascript

How to pass JSON object to controller method in ASP.NET MVC 4
so you can either use a webapi, or if I remember correctly, you can just add [HttpPost] to the line above your controller method: [HttpPost] public ActionResult ActivationManagement(String jsonData) now the body of your ajax request will need to be a string, and you'll have to convert the string to an object you can manipulate on the server side, so if you know what to expect from the JSON object, you might consider defining your own custom object and then letting MVC parse the body to your custom object. e.g. public CustomObject () { public string id {get;set;} public string address {get;set;} } ... [HttpPost] public ActionResult ActivationManagement(CustomObject jsonData) Sorry, I'm a little rusty on MVC, but I think this is the general idea.

Categories : Jquery

How to get controller to set ObjectId from posted JSON object
I've never had much luck using the default Model Binder for deserializing JSON. Try using Newtonsoft's library, I believe it is included with MVC 4 projects in Visual Studio 2012. If not you should be able to find it in the Nuget Package Manager. You can either create a custom Model Binder for User and deserialize the object there or you could make the user parameter to you SaveOrUpdateUser a string instead and then do the deserialization there. In either case the code is simply: Newtonsoft.Json.JsonConvert.DeserializeObject<User>(jsonString) Newtonsoft's JSON deserialization is pretty sophisticated and I was very impressed with how it just worked, even on deserializing some JSON into a custom object that had a Dictionary of another custom type as one of its properties. That

Categories : C#

How retrieve a JSON object in a GSP view from a controller
To get a variable like that: <g:set var="results" value="${g.include(controller: "alojamiento", action: "uploadImage", params: [idAlojamiento:alojamientoInstance.id])}" /> <g:each in="${JSON.parse(results)}"> <img src="${it.thumbnail_url}"/> </g:each> However I should mention that you should just send this down the initial call. Put the logic in a service to make it reusable. Edit: Forgot it was a string

Categories : Json

Knockout object passed to Controller as JSon MVC ASP.Net
I would try changing your code to call the stored self reference in your Ajax call as follows: $.ajax(location.href,{ data: ko.toJSON({ task: self.availableMeals });, type: 'POST', dataType:'json', contentType: 'application/json', success: function (result) { alert(result) } }); }; I'm guessing that you are having a scope issues where this is losing it's reference in your Ajax call.

Categories : Ajax

creating res.cookie in JSON format with value as object
The option of passing an Object to res.cookie() and having it auto-stringified as JSON is a new feature of Express 3.x. For Express 2.x, you'll need to stringify it yourself when creating the cookie: function createCookie(res, loginToken, user) { var jsonValue = JSON.stringify({ 'logintoken': loginToken.cookieValue, 'user_id' : user.id, 'username' : user.name }); res.cookie( 'testcookie', jsonValue, { expires: new Date(Date.now() + 2 * 604800000), path: '/' } ); } And probably have to parse it yourself as well: var testcookie = JSON.parse(req.cookies.testcookie);

Categories : Javascript

Creating a nested JSON object dynamically?
This is a dependency problem. I can already tell you ahead of time that you will need to figure out a way to handle circular dependencies (you don't want to get thrown into an infinite loop/recursion when trying to generate the output). Let's go through the basic algorithm. What are some things we need? We need a way to parse the formulas so that they're meaningful. For this example, I'm gonna assume that we'll get an input that's of the form a + b + c, where I only expect the item and + to delimit each item. We need a way to recurse down an item's dependencies to create nested childcomponents. // assuming jsonData is available in this scope function getStructure (elem) { elem = $.trim(elem); // handling an element that doesn't exist in jsonData if (!jsonData[elem]) {

Categories : Javascript

Creating a JSON object from dynamic checkboxes
jsFiddle Remove the value from the checkbox names, so they become: <input id="qual" name="qual[]" type="checkbox" value="1"> ^ nothing in here <input id="unit" name="unit[]" type="checkbox" value="7"> Also your .each is wrong. You're passing a string as the first argument, but you need to wrap the selector with jQuery $(), change to: $.each($('input[name="qual[]"]:checked'), function() { and $.each($('input[name="unit[]"]:checked'), function() { Then for your final JSON: var json = JSON.stringify({ qualifications : qualifications, units : units }); Outputs (with all checked): { "qualifications": [ "1", "7" ], "units": [ "7", "3", "1" ] }

Categories : Javascript

Passing model with dynamic json object to MVC controller
As there seemed to be no solid answers I just had to do an extra step in the jquery ajax to convert all "metadata" fields into a json string, then store it as a string on the server. Then if I need to access or change the data I use the web helper Json.Encode/Decode which returns a dynamic, then I can just add child elements which I do as: Anonymous type for simple included json object List for an array element Then I just encode it again casting the dynamic as an object.

Categories : C#

Creating json using jackson and ignoring object in some condition
Try out @JsonView. It allows you to conditionally include/suppress properties based on a view (a marker class) that is provided during serialization. class Test { private String testName; @JsonView(SomeCondition.class) private Set<Question> questions; } @GET @Path("/testWithCondition") @JsonView(SomeCondition.class) public Response getTestWithCondition() { Test test = testService.lookupTest(); return Response.ok(test).build(); } Note: You may have to disable MapperFeature.DEFAULT_VIEW_INCLUSION on your ObjectMapper.

Categories : Java

Passing JSON object as parameter from View to Controller function?
Should it not be Ext.Msg.alert(collection["Order"])? Or if you want to keep Ext.Msg.alert the way it is fieldCollection should be defined this way var fieldCollection = { Order : 'ordNumber', Ref : 'refNumber' };

Categories : Extjs

Setting a property in grunt is creating an unwanted json object
This should work: grunt.config('projects').forEach(function(project) { grunt.config.data.less.development.files[project + '.less'] = 'project/' + project + '.css'; }); Basically, you want to use that concatenated string with the .less as the key so you can access it directly through the grunt.config.data.less.development.files object using square bracket notation. That assumes you already have a placeholder for it like: grunt.config.init({ less:{ development:{ files:[] } } })

Categories : Javascript

Creating Object Properties in JSON (Javascript) Dynamically in a Method
Use this to refer to the current instance: MyObject.prototype = { // different methods and properties _randomMethod: function MyObject_randomMethod() { this.myArray = []; }, }; http://jsfiddle.net/5jSe3/

Categories : Javascript

How do I pass a JSON object as well as a simple string to a controller via an AJAX call?
One quick approach would be to just add it to the URL as a query string parameter: url: "http://localhost/x/api/awards/directors?operation=I" or, if you have a variable for it: url: "http://localhost/x/api/awards/directors?operation=" + operationValue Another option would be to add the "operation" value to the JSON object itself. I don't know what a Director is in your code, but for the sake of argument let's say it's this: { "ID" : 1, "Name" : "John" } Then you could add another value to that JSON object: { "ID" : 1, "Name" : "John", "operation" : "I" } This won't confuse the model binding for the server-side action method parameters. The JSON object doesn't need to exactly line up with one of the models. The model binding is going to make a best effort

Categories : Ajax

Creating a form for a controller inside the show of another controller
Try this @post.candidatures.build @post.candidatures.each {|candidature| candidature.responses.build } But as I wrote in comment you overcomplicated the model structure and I belive you should rethink it.

Categories : Ruby On Rails

Python - Chaining methods: returning `self` vs returning a new cloned object
Django does this so that the base query can be kept around and reused, without inheriting changes from a future "child" query, like your exclude() on your filter(). I'm guessing somebody tried storing queries for later, and realized that didn't work well without copying. I cloned the django repo and did a quick git log on django/db/models/query.py, searching for the phrase clone. The patch that introduces this change is here: https://github.com/django/django/commit/d4a3a4b

Categories : Python

how to make json object from an element in json object with unique values in underscore js
var col = [ { "MerchantName": "Fashion and You", "BrandList": " Nike, Fila", "MerchantImage": "Fashion-You-medium.jpeg" }, { "MerchantName": "Fashion and You", "BrandList": " Levis, Fasttrack, Fila", "MerchantImage": "Fashion-You-medium.jpeg" }, { "MerchantName": "ebay", "BrandList": "Nokia,HTC,Samsung", "MerchantImage": "ebay.jpeg" }, { "MerchantName": "amazon", "BrandList": "Apple,Dell,Samsung", "MerchantImage": "amazon.jpeg" }, { "MerchantName": "amazon", "BrandList": " pepe jeans, peter england, red tape", "MerchantImage, Fila": "amazon.jpeg" } ]; var brands = []; //get unique brands _.each(col, function(i){ brands = _.union

Categories : Javascript

Ajax json always returning error although json format in response is correct
Indeed the string <!-- 0.375s --> is breaking your code. Try to find out where it is comming from. Some steps: What layout are you using to render this? Try debug($this->layout) in your Controleler to see which on it is. This may very well be in there since I don't see you setting the layout to ajax for example. Cake has this ajax layout, which essentially is an empty layout. It should not contain anything more than echo $content_for_layout; in CakePHP 1.3. Check and be sure that your is "spitted out" UTF-8 encoded. This is a must for JSON. Try replacing your current view code with echo json_encode($response); or to keep the trilateral check: echo isset($response) ? json_encode($response) : ''; The JavaScriptHelper will to the same thing anyway. This "strange string" may very we

Categories : Ajax

Returning control codes as JSON to a jquery ajax json call
Firstly, try using a different ascii code. Character 1F is a "Unit separator". (It's unprintable). Check here. [Edit: try x20. It is a space.] [Edit 2: since you want unit separator and jQuery.parseJSON does not seems to like it, we will use eval(). Now, specifying dataType as 'json' will parse the response from the server; there's no need to manually parse it yourself: We will specific dataType as 'text' and manually parse json with eval(): $.ajax({ url: "/jsontest.asp", type: "POST", cache: false, dataType: "text", success: function(data) { // data is "{"val1":123,"val2":"abcx1Fdef"}" var o = eval("(" + data + ')'); // parse json // will split the text using x1F as delimiter var separated = o.val2.split('x1F'); // sepa

Categories : Jquery

Returning valid JSON from JSON Formatter on HTTP OK for WebAPI
Not sure what is the best practice here and may be someone from ASP.NET Web API team can answer but this works. public HttpResponseMessage Get() { return Request.CreateResponse<object>(HttpStatusCode.OK, new object()); }

Categories : C#

Json.NET adding backslash while returning json serialized string
No. it doesn't class Program { class Book { public int ID; public string BookName; } static void Main() { var books = new List<Book> { new Book { ID = 1, BookName = "A" }, new Book { ID = 2, BookName = "B" } }; var x = from d in books select new { ID = d.ID, BookName = d.BookName }; string str = JsonConvert.SerializeObject(x.ToList()); Console.WriteLine(str); } } There could be two problems: A) You are looking at the result from the debugger. To check for this, Put the JsonConvert in a temporary variable (like I did) and look at it with the debugger. Click on the arrow right of the hourglass and select Text Visualizer. or B) The calling method is transformi

Categories : C#

Create a empty JSON object from an existing JSON object array
You can use an object literal to store whatever you want. It is just a bag of properties (i.e. name) and values. e.g. var order = {}; Then an array literal could be used to hold the orders. e.g var orders = []; orders.push(order); But it would be just as easy to use another object literal with the id as a property. But it seems like you want some sort of validation. Perhaps something to manage the order data and handle the validation, etc. Like so: orderManager.dataStore = { _data: {}, //_redundantData = []; //could easily store in an array if id isn't unique get: function (id) { return this._data[id]; }, getAll: function () { return this._data; }, set: function (id, order) { validateOrder(order); this._data[id] = order; }, clear: function (id)

Categories : Javascript

Order JSON object alphabetical and return to JSON object
write a compare function function compare(a,b) { if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; } then sort your data var cities = {}; $.getJSON('http://mypage.com/json/cities.php', function(data){ data.sort(compare); $.each(data, function (k, vali) { cities[vali.cid] = vali.name; }); });

Categories : Jquery

JSON.NET: Serialize json string property into json object
You need a converter to do that, here is an example: public class RawJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteRawValue(value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { return typeof(string).IsAssignableFrom(objectType); } public override bool CanRead { get { return false; } } } Then decorate your class with it: public class Foo { public int Id; [JsonConverter(typeof(RawJsonConverter))] public string RawData; } Then, when you use:

Categories : C#

Knockout.js Dynamic HTML Binding returning [object Object]
Your optionText is indeed an Option object. Try: htmlContent += item.optionText.optionText; UPDATE: The real problem lies here: function PagesViewModel(pageNo, pageHeader, questions) { this.pageNumber = ko.observable(pageNo); this.pageHeaderText = ko.observable(pageHeader); this.questionItems = ko.observableArray($.map(questions, function (n) { return [new QuestionViewModel(n.questionType, n.questionNumber, n.questionText, n.pointsBudget, n.options)] })); } When you're creating your PagesViewModel, the questions parameter is already an array of QuestionViewModel objects, and by assigning this.questionItems with your custom function, you're re-creating the QuestionViewModel, passing it n.options that is already an array of Option objects thus re-wrapping it

Categories : Javascript

How to commit an object from a get controller to a post controller?
You need to either use HttpSession attributes or flash attributes (which use the HttpSession anyway). To use flash attributes, Spring makes available the RedirectAttributes class. In your GET handler @RequestMapping(value = "/benutzerverwaltung/{benutzerID}/kennwort", method = RequestMethod.GET) public String BenutzerverwaltungKennwort(@PathVariable("benutzerID")int id, @ModelAttribute("benutzer") CBenutzer benutzer, Model model, RedirectAttributes redirectAttrs){ benutzer.getBenutzer(id); benutzer.setPasswort(null); redirectAttrs.addFlashAttribute("benutzer", benutzer); return "benutzerverwaltung/kennwort"; } From the javadoc: After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL. This will be true

Categories : Java

ASP.NET MVC 3 Returning .csv file from controller
You should explicitly specify the desired file name - then your users will be able to see it in download dialog: return File(service.initiateCsvGeneration(1), "text/csv", "myfile.csv");

Categories : Asp Net Mvc

Returning XML file from Controller
With Spring MVC it's possible to map static files to a path using mvc:resources. <mvc:resources mapping="/files/**" location="/static-resources" /> It's best to place the static files outside the WEB-INF directory since this directory is supposed to be publicly inaccessible.

Categories : Xml

Function returning an object by value or nothing if object doesn't exists
You can use the "Option Pattern". The basic idea is: template <typename T> class Optional { private: bool valueIsPresent; T value; } Then, from the function you can return Optional<YourType>. Client code can then check if a value is effectively present before trying to access it and use it.

Categories : C++



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.