JSON Serialization In ASP.NET MVC And AngularJs

2 minute read

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.
<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

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.
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

@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></td>
                    <td></td>
                    <td></td>
                    <td></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.
    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

Comments