JavaScript Object Notation (JSON) is highly used in today’s communication. The main reason is that it does not depend on the programming languages that you use for programming. In simple terms, a JSON object that is returned by a .NET application can be easily read by a Java Application. The only requirement is a particular URL that returns a single or many JSON objects.
A common example is Twitter’s Public Timeline.http://twitter.com/statuses/public_timeline.json
As usual you can create new ASP.NET MVC 3 Application or can use an existing one. In ASP.NET MVC, we do usually return a JSON object through a controller. For an example, I do create a user class which is a model.
1
2
3
4
5
6
7
8
| class User { public int UserID{ get ; set ; } public string UserName{ get ; set ; } public string FirstName{ get ; set ; } public string LastName{ get ; set ; } public DateTime RegistrationTime{ get ; set ; } } |
Then I create a method that returns a JsonResult in the HomeController. The JsonResult that it returns is an instance of a User.
1
2
3
4
5
6
7
8
9
10
| public JsonResult UserInfo() { User user= new User(); user.UserID = 1; user.UserName = "Rockmarley" ; user.FirstName = "Malin" ; user.LastName = "De Silva" ; user.RegistrationTime = DateTime.Now; return this .Json(user,JsonRequestBehavior.AllowGet); } |
Then browse the URL http://localhost:52446/Home/UserInfo {Change the port as it is configured on yours}
Here you do not need to have a View for the method specified in the controller. Since it does not return an ActionResult, the View will not be taken into the count even if it was there.
No comments:
Post a Comment