Home Asp.net MVC Asp.Net Mvc Ajax Project Step by Step

Asp.Net Mvc Ajax Project Step by Step

11 min read
0
0
1,920

This Asp.Net Mvc using Ajax Project will teach you how to do basic database functions that are CREATE RETIEVE UPDATE and DELETE. using Microsoft sqlserver. The INSERT, SELECT, UPDATE and DELETE statements can be used in any database system, because this is support by all relational database systems.

We will learn how to INSERT, SELECT, UPDATE and DELETE in database by writing code to manage the records table in the database named vmschool.  records table consist of following columns Student course,name.

i explained the video tutorial below how the model view control works more clearly and how to associate with Ajax.

Index.cshtml

@{
    ViewBag.Title = "View1";
    Layout = "~/Views/Shared/styles.cshtml";
}

    <div class="row">
        <div class="col-sm-4">
            <div class="container">
                @using (Html.BeginForm("save","lolc",FormMethod.Post))
                {
                    <div class="form-group">
                        <div>
                            <label class="form-label">Course Name</label>
                            <input type="text" id="name" name="name" class="form-control" placeholder="Name" />
                        </div>
                       

                         <div>
                                <label class="form-label">Fee</label>
                                <input type="text" id="fee" name="fee" class="form-control" placeholder="Fee" />
                        </div>

                        <div>
                                <button type="button" id="save" class="btn btn-info" onclick="addProject()">Add</button>
                        </div>

                        </div>
                    
                }

            </div>

        </div>

        <div class="col-sm-8">
            <div class="panel-body">
                <table id="tbl-school" class="table table-bordered" cellspacing="0" width="100%" align="center">
                    <thead>
                        <tr>
                            <th>Course Name</th>
                            <th>Fee</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                    </thead>
                </table>

            </div>

        </div>

    </div>


@section Scripts
{

<script src="~/Scripts/jquery-1.10.2.js"></script>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>



   <script>

       getall();
       var isNew = true;

       function addProject()
       {

           var url = '';
           var data = '';
           var method;


           if(isNew == true)
           {
               url = '/lolc/save';
               data = "{coursename : '" + $('#name').val() + "',fee : '" + $('#fee').val() + "'}";
               method = 'POST';

           }
           else
           {
               url = '/lolc/save';
               data = "{coursename : '" + $('#name').val() + "',fee : '" + $('#fee').val() + "', id: '" + ID + "'}";
               method = 'POST';

           }


           $.ajax({

               type: method,
               url: url,
               dataType: 'JSON',
               contentType: "application/json; charset=utf-8",   
               data: data,



               success: function(data)
               {
                   getall();
                   if(isNew)
                   {
                       alert("Add");
                   }

                   else
                   {
                       alert("Update");

                   }
               }
           });

       }


       function getall()
       {
           $('#tbl-school').dataTable().fnDestroy();
           $('#tbl-school').DataTable({

               "ajax": {

                   "url": '/lolc/GetCourses',
                   "type": "get",
                   "datatype" : "JSON"

               },

               "columns" :
                   [

                       {data : "coursename"},
                       { data: "fee" },
                        {
                            data: "id", "render" : function(data)
                            {
                                return '<button class= "btn btn-success" onclick = "get_course(' + data + ')"> Edit </button>';
                            }
                        },

                         {
                             data: "id", "render": function (data) {
                                 return '<button class= "btn btn-danger" onclick = "get_delete(' + data + ')"> Delete </button>';
                             }
                         }
                   ]

           })

       }

       function get_course(id)
       {
           $.ajax({

               type: 'GET',
               url: '/lolc/Edit?Id=' + id,
               dataType: 'JSON',
               contentType: "application/json; charset=utf-8",
               success : function(data)
               {
                   isNew = false;

                   ID = data.id;
                   $('#name').val(data.coursename);
                   $('#fee').val(data.fee);

               }
           });

       }



       function get_delete(id)
       {

           $.ajax({

               type: 'POST',
               url: '/lolc/Remove?Id=' + id,
               dataType: 'JSON',
               contentType: "application/json; charset=utf-8",

               success:function(data)
               {
                   alert("deleted");
                   getall();


               }

           });
       }

    </script>

   }

Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

StudentController

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication21.Models;

namespace WebApplication21.Controllers
{
    public class lolcController : Controller
    {

        lolcschoolEntities db = new lolcschoolEntities();
        //
        // GET: /lolc/
        public ActionResult Index()
        {
            return View();
        }



        public ActionResult GetCourses()
        {
            using (lolcschoolEntities db = new lolcschoolEntities())
            {

                var courses = db.records.ToList();
                return Json(new { data = courses }, JsonRequestBehavior.AllowGet);

            }
          
        }

        [HttpGet]

        public JsonResult Edit(int Id)
        {
            var course = db.records.Where(a => a.id == Id).FirstOrDefault();
            return Json(course, JsonRequestBehavior.AllowGet);
        }



        public JsonResult Remove(int Id)
        {

            bool status = false;

            var course = db.records.FirstOrDefault(a => a.id == Id);

            if(course != null)
            {
                db.records.Remove(course);
                db.SaveChanges();
                status = true;
            }

            return new JsonResult { Data = new  { status = status } };

        }


        public ActionResult save(record rec)
        {

            bool status = false;

            if(ModelState.IsValid)
            {
                using(lolcschoolEntities db = new lolcschoolEntities())
                {

                    if (rec.id > 0)
                    {
                        var v = db.records.Where(a => a.id == rec.id).FirstOrDefault();
                        if(v != null)
                        {
                            v.coursename = rec.coursename;
                            v.fee = rec.fee;
                            db.Entry(v).State = EntityState.Modified;
                        }
                        }
                        else
                        {
                            db.records.Add(rec);
                        }
                        db.SaveChanges();
                        status = true;
                    }
                }
            return new JsonResult { Data = new { status = status } };       
   }

  }
}

i have attached the video link below. which will do this tutorials step by step.

 

Load More Related Articles
Load More By admin
Load More In Asp.net MVC

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Library Management System using Spring Boot

This tutorils will teach about complete library management project.the purpose of this pro…