public JsonResult GetContacts()
        {
            List<Contact> all = null;

            using (myDatabaseEntities dc = new myDatabaseEntities())
            {

                //the following linq expression which sends data from the dc variable (database) to the contacts variable
                var contacts = (from a in dc.Contacts

                                join b in dc.Countries on a.CountryID equals b.CountryID
                                join c in dc.States on a.StateID equals c.StateID
                                select new
                                {
                                    //a contains the persons data from the database
                                    a,
                                    b.CountryName,
                                    c.StateName
                                });
                //If the variable contacts is successfully populated using above code then
                if (contacts != null)
                {
                    all = new List<Contact>();
                    foreach (var i in contacts)
                    {
                        //Create a new contact object and populate it with persons data as shown below
                        Contact con = i.a;
                        con.CountryName = i.CountryName;
                        con.StateName = i.StateName;
                        //Add con the list of con on each iterations (each row/person)
                        all.Add(con);
                    }
                }
            }
            //Data: A value that indicates whether HTTP GET requests from the client are allowed.
            //JsonRequestBehavior: Gets or sets a value that indicates whether HTTP GET requests from the client are allowed.
            return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
 //Get contact by ID
 public Contact GetContact(int contactID)
 {
     Contact contact = null;
     using (myDatabaseEntities dc = new myDatabaseEntities())
     {
         var v = (from a in dc.Contacts
                  join b in dc.Countries on a.CountryID equals b.CountryID
                  join c in dc.States on a.StateID equals c.StateID
                  where a.ContactID.Equals(contactID) //
                  select new
                  {
                      a,
                      b.CountryName,
                      c.StateName
                  }).FirstOrDefault(); //Returns the first element of a sequence, or a default value if the sequence contains no elements.
         //     contains no elements.
         if (v != null)// if the database contains a contact
         {
             contact = v.a;
             contact.CountryName = v.CountryName;
             contact.StateName = v.StateName;
         }
         return contact;
     }
 }
        public ActionResult DeleteContact(int id)
        {
            bool status = false;
            string message = "";
            using (myDatabaseEntities dc = new myDatabaseEntities())
            {
                //Get contact to be deleted
                var v = dc.Contacts.Where(a => a.ContactID.Equals(id)).FirstOrDefault();
                //If contact to be deleted exists in the database (dc)
                if (v != null)
                {

                    // .Remove(...) : Removes the given collection of entities from the context underlying the
                    //     set with each entity being put into the Deleted state such that it will be
                    //     deleted from the database when SaveChanges is called.

                    //Remove the contact from the database
                    dc.Contacts.Remove(v);

                    //Refresh the database
                    // Saves all changes made in this context to the underlying database.
                    dc.SaveChanges();
                    status = true;
                    message = "Successfully Deleted!";
                }
                else
                {
                    return HttpNotFound();
                }
            }
            //Return status of the deletion and message "Successfully Deleted!"
            return new JsonResult { Data = new { status = status, message = message } };
        }
        //Get contact by ID
        public Contact GetContact(int contactID)
        {
            Contact contact = null;

            using (myDatabaseEntities dc = new myDatabaseEntities())
            {
                var v = (from a in dc.Contacts
                         join b in dc.Countries on a.CountryID equals b.CountryID
                         join c in dc.States on a.StateID equals c.StateID
                         where a.ContactID.Equals(contactID) //
                         select new
                {
                    a,
                    b.CountryName,
                    c.StateName
                }).FirstOrDefault(); //Returns the first element of a sequence, or a default value if the sequence contains no elements.
                //     contains no elements.
                if (v != null)       // if the database contains a contact
                {
                    contact             = v.a;
                    contact.CountryName = v.CountryName;
                    contact.StateName   = v.StateName;
                }
                return(contact);
            }
        }
 //Fetch State from database
 private List <State> GetState(int countryID)
 {
     using (myDatabaseEntities dc = new myDatabaseEntities())
     {
         return(dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList());
     }
 }
 //Fetch Country from database
 private List <Country> GetCountry()
 {
     using (myDatabaseEntities dc = new myDatabaseEntities())
     {
         return(dc.Countries.OrderBy(a => a.CountryName).ToList());
     }
 }
        public ActionResult DeleteContact(int id)
        {
            bool   status  = false;
            string message = "";

            using (myDatabaseEntities dc = new myDatabaseEntities())
            {
                //Get contact to be deleted
                var v = dc.Contacts.Where(a => a.ContactID.Equals(id)).FirstOrDefault();
                //If contact to be deleted exists in the database (dc)
                if (v != null)
                {
                    // .Remove(...) : Removes the given collection of entities from the context underlying the
                    //     set with each entity being put into the Deleted state such that it will be
                    //     deleted from the database when SaveChanges is called.

                    //Remove the contact from the database
                    dc.Contacts.Remove(v);

                    //Refresh the database
                    // Saves all changes made in this context to the underlying database.
                    dc.SaveChanges();
                    status  = true;
                    message = "Successfully Deleted!";
                }
                else
                {
                    return(HttpNotFound());
                }
            }
            //Return status of the deletion and message "Successfully Deleted!"
            return(new JsonResult {
                Data = new { status = status, message = message }
            });
        }
 //return states as json data
 public JsonResult GetStateList(int countryID)
 {
     using (myDatabaseEntities dc = new myDatabaseEntities())
     {
         return(new JsonResult {
             Data = GetState(countryID), JsonRequestBehavior = JsonRequestBehavior.AllowGet
         });
     }
 }
        public JsonResult GetContacts()
        {
            List <Contact> all = null;

            using (myDatabaseEntities dc = new myDatabaseEntities())
            {
                //the following linq expression which sends data from the dc variable (database) to the contacts variable
                var contacts = (from a in dc.Contacts

                                join b in dc.Countries on a.CountryID equals b.CountryID
                                join c in dc.States on a.StateID equals c.StateID
                                select new
                {
                    //a contains the persons data from the database
                    a,
                    b.CountryName,
                    c.StateName
                });
                //If the variable contacts is successfully populated using above code then
                if (contacts != null)
                {
                    all = new List <Contact>();
                    foreach (var i in contacts)
                    {
                        //Create a new contact object and populate it with persons data as shown below
                        Contact con = i.a;
                        con.CountryName = i.CountryName;
                        con.StateName   = i.StateName;
                        //Add con the list of con on each iterations (each row/person)
                        all.Add(con);
                    }
                }
            }
            //Data: A value that indicates whether HTTP GET requests from the client are allowed.
            //JsonRequestBehavior: Gets or sets a value that indicates whether HTTP GET requests from the client are allowed.
            return(new JsonResult {
                Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
 //Fetch State from database
 private List<State> GetState(int countryID)
 {
     using (myDatabaseEntities dc = new myDatabaseEntities())
     {
         return dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
     }
 }
 //Fetch Country from database
 private List<Country> GetCountry()
 {
     using (myDatabaseEntities dc = new myDatabaseEntities())
     {
         return dc.Countries.OrderBy(a => a.CountryName).ToList();
     }
 }
        public ActionResult Save(Contact c)
        {
            string message = "";
            bool status = false;

            #region
            //ModelState.IsValid tells you if any model errors have been added to ModelState. The ModelState represents the submitted values and errors in said values during a POST.
            //The validation process respects the attributes like Required and EmailAddress, and we can add custom errors to the validation if we so desire. ValidationSummary and ValidationMessageFor read directly from ModelState to display errors to the user.
            //ModelState has two purposes: to store the value submitted to the server, and to store the validation errors associated with those values.
            //IsValid: Gets a value that indicates whether this instance of the model-state dictionary
            //     is valid.
            //Returns:
            //     true if this instance is valid; otherwise, false.
            #endregion
            if (ModelState.IsValid)
            {
                using (myDatabaseEntities dc = new myDatabaseEntities())
                {
                    //If there is a contact in the database then update it as follows
                    if (c.ContactID > 0)
                    {
                        //.Equals(): Returns
                        //     true if obj has the same value as this instance; otherwise, false.

                        //FirstOrDefault(): Returns the first element of a sequence, or a default value if the sequence
                        //     contains no elements.

                        //We are providing Contact c as an argument to the Post method Save
                        //v = Contact c if it exists in the database a
                        var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
                        //create contact if does not already exists,
                        //collect data in variable v using argument provided c.
                        if (v != null)
                        {
                            v.ContactPerson = c.ContactPerson;
                            v.ContactNo = c.ContactNo;
                            v.CountryID = c.CountryID;
                            v.StateID = c.StateID;
                        }
                        else
                        {
                            return HttpNotFound();
                        }
                    }
                    else
                    {
                        // add new contact to the database
                        dc.Contacts.Add(c);
                    }
                    //Saves all changes made in this context to the underlying database.
                    dc.SaveChanges();
                    status = true;
                    message = "Successfully Saved.";
                }
            }
            else
            {
                message = "Error! Please try again.";
            }

            //Data returned : status of the Save (failure or success)
            //message : return the variable message 's value we previously initialized
            return new JsonResult { Data = new { status = status, message = message } };
        }
 //return states as json data
 public JsonResult GetStateList(int countryID)
 {
     using (myDatabaseEntities dc = new myDatabaseEntities())
     {
         return new JsonResult { Data = GetState(countryID), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
     }
 }
예제 #14
0
        public ActionResult Save(Contact c)
        {
            string message = "";
            bool   status  = false;

            #region
            //ModelState.IsValid tells you if any model errors have been added to ModelState. The ModelState represents the submitted values and errors in said values during a POST.
            //The validation process respects the attributes like Required and EmailAddress, and we can add custom errors to the validation if we so desire. ValidationSummary and ValidationMessageFor read directly from ModelState to display errors to the user.
            //ModelState has two purposes: to store the value submitted to the server, and to store the validation errors associated with those values.
            //IsValid: Gets a value that indicates whether this instance of the model-state dictionary
            //     is valid.
            //Returns:
            //     true if this instance is valid; otherwise, false.
            #endregion
            if (ModelState.IsValid)
            {
                using (myDatabaseEntities dc = new myDatabaseEntities())
                {
                    //If there is a contact in the database then update it as follows
                    if (c.ContactID > 0)
                    {
                        //.Equals(): Returns
                        //     true if obj has the same value as this instance; otherwise, false.

                        //FirstOrDefault(): Returns the first element of a sequence, or a default value if the sequence
                        //     contains no elements.

                        //We are providing Contact c as an argument to the Post method Save
                        //v = Contact c if it exists in the database a
                        var v = dc.Contacts.Where(a => a.ContactID.Equals(c.ContactID)).FirstOrDefault();
                        //create contact if does not already exists,
                        //collect data in variable v using argument provided c.
                        if (v != null)
                        {
                            v.ContactPerson = c.ContactPerson;
                            v.ContactNo     = c.ContactNo;
                            v.CountryID     = c.CountryID;
                            v.StateID       = c.StateID;
                        }
                        else
                        {
                            return(HttpNotFound());
                        }
                    }
                    else
                    {
                        // add new contact to the database
                        dc.Contacts.Add(c);
                    }
                    //Saves all changes made in this context to the underlying database.
                    dc.SaveChanges();
                    status  = true;
                    message = "Successfully Saved.";
                }
            }
            else
            {
                message = "Error! Please try again.";
            }

            //Data returned : status of the Save (failure or success)
            //message : return the variable message 's value we previously initialized
            return(new JsonResult {
                Data = new { status = status, message = message }
            });
        }
        //fetch data from the database.
        public JsonResult getEmployeeData(int page)
        {
            List<Employee> list = new List<Employee>();
            //The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
            using (myDatabaseEntities dc = new myDatabaseEntities())
            {
                int totalPage = 0;
                int totalRecord = 0;
                int pageSize = 20;

                //Populate v with data from the database.
                var v = dc.Employees.OrderBy(a => a.FirstName);
                totalRecord = v.Count();
                totalPage = (totalRecord / pageSize) + ((totalRecord % pageSize) > 0 ? 1 : 0);
                //Populate the list with data from the variable v ,data filtered is, as shown below
                list = v.Skip((page - 1) * pageSize).Take(pageSize).ToList();

                //The first argument is a json object populated with data from above.
                //The second argument is required if the request is a GET request.
                return new JsonResult { Data = new { List = list, currentPage = page, totalPage = totalPage }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };

            }
        }