Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Thursday, 13 November 2014

ASP.NET MVC: Intro to MVC Binding JSON objects to Models


This post is designed to assist in jump-starting your MVC (model-view-control) project binding JSON to models (using Ajax posts). I feel that this is a vital skill to any journeyman ASP.NET MVC developer. The sample project (available on Github) has been tested in Visual Studio 2012 and Xamarin on OS X.
If you’re new to MVC, here is a brief explanation: this design pattern is designed to keep your code into specific parts dedicated for specific usage. Models are designed to represent your data objects. The controller works with/manipulates models (backend, server side code). It then generates a View (rendered HTML) that is presented to the user on their web browser. The Model and Controller are written in C# for this project. The View is rendered in pure HTML with Javascript.
This tutorial will walk you through creating a project from start to finish. You’ll also be introduced to a cast of squirrels (such as @acommonsquirrel and Foamy the Squirrel). To get started, create a new MVC project and call it “bindingJSON” (using the standard, no authentication). Now, inspect the object you need to model. Using an object oriented approach, how would you create your item? We’ll use a common squirrel as our object; so, create a new Model in your ASP.NET project called “Squirrel.cs“. A squirrel has a few properties, such as:
  • name
  • age
  • acorns
  • gender
  • hobby
So, inside of your model you’ll have the following class:
using System;
namespace bindingJSON
{
 public class Squirrel
 {
 public string Name { get; set; }
 public int? Age { get; set; } // squirrels aren't required tell us their age
 public int Acorns { get; set; }
 public char Gender { get; set; }
 public string Hobby { get; set; }
 }
}
Next, we’ll build out a simple controller. This controller will contain an ActionResult and a JsonResult method. This will be our “HomeController.cs“. The thing to note is the use of the JsonResult. A JsonResult allows you receive an XmlHttpRequest (in Javascript) that will send JSON objects. You can send any object you want; we’re going to expect aSquirrel – incomingSquirrel. It’ll call a private function (just an example of what you can do with the object).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace bindingJSON.Controllers
{
 public class HomeController : Controller
 {
 public ActionResult Index()
 {
 // Initial View
 return View();
 }
[HttpPost]
 public JsonResult PostSquirrel(Squirrel incomingSquirrel)
 {
 string status = null;
 try { 
 saveSquirrel(incomingSquirrel);
 status = "If you don't see this, something went wrong.";
 } catch (Exception e) {
 status = e;
 }
 return Json(status);
 }
#region privateHelpers
 private Boolean saveSquirrel(Squirrel incomingSquirrel) 
 {
 return false;
 }
 #endregion
 }
}
Okay, so we have the model and controller built out. Now, we need to put together our view. We’ll call it “Home/Index.cshtml“. Inside, we’re going to have just a few small parts. For sake of simplicity, I won’t be using partial views to keep the project small. The view will put together a page that sends form data to the server (using Javascript and the JSONResult in your controller). In the view, we’ll have a simple $.ajax method (via the jQuery library) that fetches the current values of each input, places them into a JSON object, and then sends it to our server. Note that on success of the ajax call you’ll see a message in the error log. If you receive a server error (such as 500) then your model and JSON have errors (such as case sensitivity errors). Also note that you could send a Javascript array of JSON objects and have them bound on the server side using a List<Squirrel>() (ie: public ActionResult HiSquirrels(List<Squirrel> aTonOfSquirrels){}).
@model bindingJSON.Squirrel
@{
 Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
 <title>Index</title>
</head>
<script type="text/javascript" src="https://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
 // when the DOM has fully loaded...
 $("#btnSubmit").bind("click", function() {
 var onEventLaunchSquirrel = new postSquirrel();
 onEventLaunchSquirrel.launchSquirrel();
 });
 });
 function postSquirrel() {
 this.launchSquirrel = function() {
 
 // fetch values from input
 var name = $("Name").val();
 var age = $("Age").val();
 var acorns = $("Acorns").val();
 var gender = $("Gender").val();
 var hobby = $("Hobby").val();
 
 // build json object
 var squirrel = {
 Name: name,
 Age: age,
 Acorns: acorns,
 Gender: gender,
 Hobby: hobby
 };
$.ajax({
 type: "POST",
 url: "home/PostSquirrel",
 traditional: true,
 contentType: 'application/json; charset=utf-8',
 data: JSON.stringify(squirrel),
 success: function (data) { console.log(data) },
 error: function (data) { console.log(data) } 
 });
 
 }
 }
 
</script>
<body>
<header>
 <hgroup>
 <h1>oh hey, a squirrel!</h1>
 <h3>we should interview it!</h3>
 </hgroup>
</header>
<section>
 <p>If the squirrel cooperates, record their information and send it to our server.</p>
 
 <p><input type="text" required="required" id="Name" placeholder="Enter the squirrel's name" /></p>
 <p><input type="number" id="Age" placeholder="squirrel's age (optional)" /></p>
 <p><input type="number" required="required" id="Name" placeholder="How many acorns do they own?" /></p>
 <p><input type="number" required="required" id="Name" placeholder="M or F? (single letter only)" size="1" /></p>
 <p><input type="string" required="required" id="Hobby" placeholder="How many acorns do they own?" /></p>
 
 <p><input id="btnSubmit" type="button" value="launch the squirrel through the internet!" /></p>
 
 <div id="status"></div>
</section>
</body>
</html>
So, now you have your full MVC application built (well, sort of). Once you submit the form the JSON object will be send to the JSONResult method on the server side and you can do whatever you need with it.
That’s it! If you have any questions or spot any errors let me know. If anyone has problems with this working in Visual Studio I’ll put together a project in 2013.
You can grab the source code here: https://github.com/code-for-coffee/mvcBindingJson

Wednesday, 12 November 2014

JSON Serialization in ASP.NET MVC and AngularJs - Basic tutorial

In this article I will show how JSON serialize in ASP.NET MVC and bind data by AngularJs. I will not describe what and how JSON, ASP.NET MVC or AngularJs work. Hope I will discuss these topics in another article.
Let’s start to create an ASP.NET MVC project with AngularJs.
Step 1: Create ASP.NET MVC application
Open visual studio, Got to File->New->Project
Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
Select Empty Template and Razor as view engine
Step 2: Install required packages
Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package.

PM> Install-Package jQuery
PM> Install-Package angularjs -Version 1.2.26
PM> Install-Package Newtonsoft.Json
Step 3: Create a layout page
Create a layout page in Views-> Shared ->_Layout.cshtml and add reference of angularjs and jquery.
?
1
2
3
4
5
6
7
8
9
10
<html ng-app>
    <head>   
        <script src="~/Scripts/angular.min.js"></script>
        <script src="~/Scripts/jquery-2.1.1.js"></script>
        <title>Student Information</title>
    </head>
    <body>
        @RenderBody()
    </body>
</html>
Step 4: Create a view model “Student” in model folder
?
1
2
3
4
5
6
7
public class StudentVM
{
   public int RollNo { get; set; }
   public string StudentName { get; set; }
   public string Class { get; set; }
   public string ClassTeacher { get; set; }
}
Step 5: Create StudentsController
Create StudentsController in Controller folder like following. Here GetSerializedStudentVMS method serialized Student model to JSON.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class StudentsController : Controller
    {
        //
        // GET: /Students/
        public ActionResult Index()
        {
            return View("Index", "", GetSerializedStudentVMS());
        }
        public string GetSerializedStudentVMS()
        {
            var students = new[]
             {
                    new StudentVM {RollNo = 1, StudentName = "Jamal Uddin", Class="One", ClassTeacher="Mr. Anowar Hossain"},
                    new StudentVM {RollNo = 5, StudentName = "Kamal Hossain", Class="Two", ClassTeacher="Mr. Shahana Begum"},
                    new StudentVM {RollNo = 10, StudentName = "Jahid Hasan", Class="Three", ClassTeacher="Mr. Lutfor Rahman"},
                };
           
            //Used to make property name as camel case
            var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
           return JsonConvert.SerializeObject(students, Formatting.None, settings); //Returns students list as JSON
        }
    }
Step 6: Create index view
Right click of index action of StudentsController, click view and a view will automatically create to Views-> Students ->index.cshtml
Change the index.cshtml like following
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@model string
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div ng-init="students = @Html.Raw(Model)">
    <div>
        <div>
            <table>
                <tr>
                    <th>Roll No</th>
                    <th>Student Name</th>
                    <th>Class</th>
                    <th>Course Teacher</th>
                </tr>
                <tr ng-repeat="student in students">
                    <td>{{student.rollNo}}</td>
                    <td>{{student.studentName}}</td>
                    <td>{{student.class}}</td>
                    <td>{{student.classTeacher}}</td>
                </tr>
            </table>
        </div>
    </div>
</div>
Here ng-init used to initialize the json object and ng-repeat works like foreach.
Step 7: Change RouteConfig.cs
Change RouteConfig like following to run StudentController by default.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Students", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
Now run the application. Yes you will see the student information in a table. Thanks for your patient 

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...