Tuesday, May 28, 2013

Asp.net ajax CRUD sample

Many people is confusing how to use build an Asp.net ajax application. It is simple to build an ajax application using jQuery and jeasyui framework. For this sample we will create a small student management system use the EntitiesFramework, code first approach, jQuery and jeasyui to manage st

  1. Create solution structure
  2. Data access layer
  3. Business layer
  4. UI layer
1. Create solution architecture:
Use visual studio 2010 to create project structure like this:

  • JQueryCRUD.Data: use Class libraries project template
  • JQueryCRUD.Biz: use Class libraries project template
  • JQueryCRUD.UI: use Asp.net web project template
2. Data access layer:
We will use EntitiesFramework, so you have to reference EntitiesFramework from JQueryCRUD.Data project. You can use nuget to reference, how to use nuget doesn't cover in this post. You can check details here. This sample is very very simple so we only 'Student' entity.

So, we also have only  StudentRepository, it have 5 methods: Insert, Update, Delete, GetPaging and GetRecordCount.

public class Student
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

public class StudentRepository
    {
        public Student Insert(Student model)
        {
            using (var ctx = new JQueryCRUDDatabaseContext())
            {
                ctx.Students.Add(model);
                ctx.SaveChanges();
            }

            return model;
        }

        public Student Update(Student model)
        {
            using (var ctx = new JQueryCRUDDatabaseContext())
            {
                ctx.Entry(model).State = System.Data.EntityState.Modified;
                ctx.SaveChanges();
            }

            return model;
        }

        public void Delete(int id)
        {
            using (var ctx = new JQueryCRUDDatabaseContext())
            {
                var model = ctx.Students.Single(x => x.Id == id);
                ctx.Students.Remove(model);
                ctx.SaveChanges();
            }
        }

        public Student[] GetPaging(int pageIndex, int pageSize)
        {
            using (var ctx = new JQueryCRUDDatabaseContext())
            {
                return ctx.Students.OrderBy(x=>x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToArray();
            }
        }

        public int GetRecordCount()
        {
            using (var ctx = new JQueryCRUDDatabaseContext())
            {
                return ctx.Students.Count();
            }
        }
    }


3. Business layer:
In this sample, the Business layer only call to Data Acces Layer, it is very very simple.

4. UI layer:
We will use the jQuery and jeasyui for our UI layer. You can download the latest jQuery here and the latest jeasyui here.

Thank you very much to jeasyui team they did a great CRUD example here. If you want to make it work with Asp.net application I think we should create our Generic handlers to handle Insert, Update, Delete and GetPaging action.

public class GetPaging : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int page = string.IsNullOrEmpty(context.Request.Params["page"]) ? 1 : int.Parse(context.Request.Params["page"]);
            int rows = string.IsNullOrEmpty(context.Request.Params["rows"]) ? 10 : int.Parse(context.Request.Params["rows"]);
            var bizObj = new StudentService();
            context.Response.Write(JsonConvert.SerializeObject(new { total = bizObj.GetRecordCount(), rows = bizObj.GetPaging(page, rows) }));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
public class Insert : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                var newStudent = new JQueryCRUD.Data.POCO.Student();
                new StudentService().Insert(new JQueryCRUD.Data.POCO.Student
                {                    
                    FirstName = context.Request.Params["FirstName"],
                    LastName = context.Request.Params["LastName"]                  
                });
            }
            catch (Exception exception)
            {
                context.Response.Write("{'errorMsg': '" + exception.Message + ".'}");
                context.Response.End();
            }

            context.Response.Write("{'errorMsg': ''}");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
public class Update : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {                
                new StudentService().Update(new JQueryCRUD.Data.POCO.Student
                {
                    Id = int.Parse(context.Request.Params["Id"]),
                    FirstName = context.Request.Params["FirstName"],
                    LastName = context.Request.Params["LastName"]
                });
            }
            catch (Exception exception)
            {
                context.Response.Write("{'errorMsg': '" + exception.Message + ".'}");
                context.Response.End();
            }

            context.Response.Write("{'errorMsg': ''}");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
public class Delete : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                new StudentService().Delete(int.Parse(context.Request.Params["Id"]));
            }
            catch (Exception exception)
            {
                context.Response.Write("{'errorMsg': '" + exception.Message + ".'}");
                context.Response.End();
            }

            context.Response.Write("{'errorMsg': ''}");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

That's it. You can download complete sample here. Let me know if you have any problem with this sample.

No comments:

Post a Comment