Click here to Skip to main content
15,881,281 members
Articles / Web Development / ASP.NET

MVC Basic Site: Step 3 – Dynamic Layouts and Site Admin with: AJAX, jqGrid, Controller Extensions, HTML Helpers, and more

Rate me:
Please Sign up or sign in to vote.
4.96/5 (72 votes)
25 Oct 2013Ms-PL28 min read 205.8K   13.1K   186  
This article provides the implementation of dynamic layouts and web site administration in ASP.NET MVC4.0 by using: AJAX, jqGrid, Custom Action Results, Controller Extension, HTML Helpers, and more.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;
//
using MvcBasic.Logic;
using MvcBasicSite.Models.Grid;
using MvcBasicSite.Models.Helpers;

namespace MvcBasicSite.Controllers
{
    /// <summary>
    /// Defines the visitor log controller.
    /// </summary>
    public class VisitorLogController : BaseController
    {

        /// <summary>
        /// The flag used to notify that the view was created from Index method.
        /// </summary>
        private static bool _fromIndex = false;

        /// <summary>
        ///  Get Visitor log sorted by date.
        /// </summary>
        /// <returns>VisitorLog view</returns>
        [Authorize]
        public ActionResult Index()
        {
            _fromIndex = true;
            //
            return View();
        }

        /// <summary>
        /// Activate Delete view for the current item from the grid.
        /// </summary>
        /// <param name="id">The item ID.</param>
        /// <param name="gridSettings">The grid settings.</param>
        /// <returns>The action result.</returns>
        [Authorize]
        public ActionResult Delete(int id, string gridSettings)
        {
            if (gridSettings != null)
                Session["VisitorLogGridSettings"] = gridSettings; // Cache the Grid Settings!
            //
            VisitorLog visitorLog = _db.VisitorLogs.Single(u => u.ID == id);
            //
            return View(visitorLog);
        }

        /// <summary>
        /// Delete the current item.
        /// </summary>
        /// <param name="id">The item ID.</param>
        /// <returns>The action result.</returns>
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            VisitorLog visitorLog = _db.VisitorLogs.Single(u => u.ID == id);
            _db.VisitorLogs.DeleteObject(visitorLog);
            _db.SaveChanges();
            //
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Search by using start date and from date from request.
        /// </summary>
        /// <returns></returns>
        //[Authorize]
        public PartialViewResult Search()
        {
            string startDate = Request["from"];
            string endDate = Request["to"];
            //
            // Cache the start and end dates into the session to be used by later one in the view.
            //
            Session["StartDate"] = (startDate.Length < 1 ? null : (object)DateTime.Parse(startDate, Thread.CurrentThread.CurrentCulture));
            Session["EndDate"] = (endDate.Length < 1 ? null : (object)DateTime.Parse(endDate, Thread.CurrentThread.CurrentCulture));
            //
            return PartialView("_VisitorLogGrid");
        }

        /// <summary>
        /// Load the data that will be used by the jqGrid by using the given grid settings.
        /// </summary>
        /// <param name="grid">The grid sesstings.</param>
        /// <returns>The data in JSON format.</returns>
        public JsonResult GetData(GridSettings grid)
        {
            if (_fromIndex && Session["VisitorLogGridSettings"] != null)
            {
                //
                // Get grid settings from cache!
                //
                grid = new GridSettings((string)Session["VisitorLogGridSettings"]);
            }
            //
            _fromIndex = false; // Must be set on false here!
            //
            // Load the data from the database for the current grid settings.
            //
            DateTime searchStartDate = (Session["StartDate"] == null ? DateTime.MinValue : (DateTime)Session["StartDate"]);
            DateTime searchEndDate = (Session["EndDate"] == null ? DateTime.MinValue : (DateTime)Session["EndDate"]);
            int count;
            var query = grid.LoadGridData<VisitorLog>(VisitorLog.SearchLogByDates(_db, searchStartDate, searchEndDate), out count);
            var data = query.ToArray();
            //
            // Convert the results in grid format.
            //
            string gridSettingsString = grid.ToString(); // Used to preserve grid settings!
            Session["VisitorLogGridSettings"] = gridSettingsString;
            gridSettingsString = null;
            var result = new
            {
                total = (int)Math.Ceiling((double)count / grid.PageSize),
                page = grid.PageIndex,
                records = count,
                rows = (from host in data
                        select new
                        {
                            ID = host.ID,
                            VisitorName = GetVisitorNameForBinding(host),
                            StartDate = host.StartDate.ToString(),
                            EndDate = host.EndDate.ToString(),
                            WasTimeOut = (host.WasTimeOut ?? false),
                            Action = string.Format("{0}", 
                                            RenderHelpers.ImageButton(
                                                    this, 
                                                    Resources.Resource.DeleteTip,
                                                    "~/Content/Images/Delete.gif",
                                                    "Delete", 
                                                    new { id = host.ID }, 
                                                    new { style = "border:0px;" }))
                        }).ToArray()
            };
            //
            // Convert to JSON before to return.
            //
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Get/Render the visitor name for binding.
        /// </summary>
        /// <param name="host">The visitor log.</param>
        /// <returns>The rendered object.</returns>
        private string GetVisitorNameForBinding(VisitorLog host)
        {
            return host.User == null ? Resources.Resource.VisitorLogIndexAnonymous: host.User.Username;
        }

        /// <summary>
        /// Clear all order's history grid data.
        /// </summary>
        /// <returns>Returns the result view.</returns>
        [Authorize]
        public ActionResult ClearGridData()
        {
            DateTime searchStartDate = (Session["StartDate"] == null ? DateTime.MinValue : (DateTime)Session["StartDate"]);
            DateTime searchEndDate = (Session["EndDate"] == null ? DateTime.MinValue : (DateTime)Session["EndDate"]);
            VisitorLog.DeleteLogByDates(_db, searchStartDate, searchEndDate);
            //
            return RedirectToAction("Index");
        }

       
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Romania Romania
I have about 20 years experiences in leading software projects and teams and about 25 years of working experience in software development (SW Developer, SW Lead, SW Architect, SW PM, SW Manager/Group Leader).

Comments and Discussions