Formatting JSON in ASP.NET MVC -


I want to return a JSON with ASP.NET MVC action, the result type method that looks like this: true, user: [id: 1, filename: 'text22'}, {id: 2, filename: 'text 23'}]}

How do I format it? Right now I have something like this

  returns Jason (new {with key. Success = "true", key.username = responseJsonString}, JsonRequestBehavior.AllowGet)   

EDIT: I am using VB.NET but the answer in C # is also fine.

I prefer manually using ViewModels instead of creating complex JSON responses Ensures that the data come back, and the strongly typed properties are easy to work with IMHO. public class reaction {receives public success; Set; } Public IEnumerable & lt; Users & gt; User {Received; Set; }} Public class user {public id id (get; set;} public string name {get} set;}}

and then just:

  Response Response = New Response (); Response. Returns to Success = True; // Jason (Response) to the rest of the data;   

Additionally, you use a base class for each response The advantage of doing is, if there are general data like success status, or error message. Public Class Response {Public Child Success {Received; Set;} Public String Message {get} Set;}} Public Category UserResponse: Responsebase {Ienumerable & lt; User & gt; Users}; Now, if you have any errors:

  returns Jason (new responsebase) {successful = false, message = "your error"}   

});

or if it succeeds

  returns Jason (new user response) {successful = true, user = usage Actor}); If you want to manually craft JSON, then just:   Jason returns (new {success = true, users = new [] {new {id = 1, name = "Alice"}, new {id = 2, name = "bob"}}});    

Comments

Popular posts from this blog

Python SQLAlchemy:AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'schema' -

java - How not to audit a join table and related entities using Hibernate Envers? -

mongodb - CakePHP paginator ignoring order, but only for certain values -