Tuesday, April 5, 2016

Tree View in MVC 4

Add and Delete Node

Index.chtml

@model IEnumerable<Models.TreeViewNodeVM>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <style type="text/css">
     h2{font-family: 'segoe_uilight', Arial !important; font-size:22px; margin-bottom:10px;}
     #tree li{font-weight:bold;font-family: 'segoe_uilight', Arial !important; position:relative;}
     #tree li a{ margin-bottom:5px;}
     #tree ul{margin:0px 0 0px 0px;}
     #tree ul li{ font-weight:normal; margin-bottom:0; }
     #tree ul li a{margin-bottom:0; }
     #tree ul li a ul li a{margin-bottom:0; color:green;}
     #tree ul li a ul li a ul li a{margin-bottom:0; color:yellow;}
     #tree .toggleTxt{ margin:5px 0 5px 25px;}
     .mainHead{ color:#ff0000; background:url(../css/images/downArrow.png) no-repeat left -3px; padding-left:25px;}
     .aSelected{color:#0ac324; background-color:#ff6a00;}
     .arrowToggle{ display:inline-block; position:absolute; top:1px; left:5px; background:#fff; font-size:22px; line-height:12px; width:15px; text-align:center; padding-bottom:2px; cursor:pointer;}
     .inputbtn{top:1px; left:5px; color:#fff; background:green; font-size:15px; line-height:12px; width:15px; text-align:center; padding-bottom:2px; cursor:pointer; font-weight:bold; border:1px;}
 </style>
<script type="text/javascript">
    var GlobalParentCategory =0;
    function additem()
    {
        var id = $('.aSelected').attr("id");
        var randomnumber = Math.random().toString().slice(2, 5);
        var title = "New Category" + randomnumber;
        if (id != null) {
            $.ajax({
                url: '../mediacategory/AddTitle',
                contentType: "application/json",
                type: "Get",
                data: { id: id, title: title },
                success: function (result) {
                    onnewcategory(result);
                    $('#' + id + '').next("div:first").css({ "display": "block" }).prepend('<ul><li><a onclick="onnewcategory(this.id)" id="' + result + '">New Category' + randomnumber + '<a/><div class="toggleTxt"></div></li></ul>')
                }
            });
        }
        else {
            id = 0;
            $.ajax({
                url: '../mediacategory/AddTitle',
                contentType: "application/json",
                type: "Get",
                data: { id: id, title: title },
                success: function (result) {
                    onnewcategory(result);
                    $('#' + id + '').next("div:first").css({ "display": "block" }).prepend('<ul><li><a onclick="onnewcategory(this.id)" id="' + result + '">New Category' + randomnumber + '<a/><div class="toggleTxt"></div></li></ul>')
                }
            });
        }
    }
    function onnewcategory(id)
    {
        $.ajax({
            type: 'POST',
            url: '@Url.Content("~/CategoryTree/ShowCategoryForm")',
            data:{id:id},
            success: function (result) {
                $('#formDiv').html(result);
                //$.validator.unobtrusive.parse($('#formDiv'))
        }
        });
    }
    function onaclick(id)
    {
        $('.aSelected').removeClass('aSelected');
        $('#' + id + '').addClass('aSelected');
    }
 
    function deleteitem() {
        var id = $('.aSelected').attr("id");
        if (id != null) {
            $.ajax({
                url: '../mediacategory/DeleteTitle',
                contentType: "application/json",
                type: "Get",
                data: { id: id },
                success: function (result) {
                    if (result) {
                        //alert(result);
                        location.href = "../categorytree/index";
                    }
                    else {
                        alert('You can not delete parent.');
                    }
                }
            });
        }
        else {
            alert('Please select item !.');
        }
    }
</script>
<div class="contentContainerBlack" id="SearchContainer">
    <div class="clearfix">
        <span class="mainHeading fLeft">Media Categories</span>
        <span class="fRight"><a href="../medialibrary/index" class="addBtn addEditRecord" id="0">Media Library</a></span>
    </div>
</div>
<div class="clearfix" style="width:100%;">
<div style="width:450px; float:left; border-right:1px solid #ccc; margin-left:20px; overflow:auto;">
<table>
    <tr><td>&nbsp;</td></tr>
    <tr>
    <td><a onclick="additem()" class="inputbtn">Add</a></td>
        <td>&nbsp;</td>
   @* <td><a onclick="edititem()">Edit</a></td>*@
    <td><a onclick="deleteitem()" class="inputbtn">Delete</a></td>
</tr><tr><td>&nbsp;</td></tr></table>
<div id="treeDemo">
    <ul id="tree">
        @foreach (var tNode in Model)
        {
        <li>
            <span class="arrowToggle">-</span>
            <a class="mainHead" onclick="onaclick(this.id)" id="@tNode.Id"> @tNode.NodeName</a>
            <div class="toggleTxt">
                  @Html.Partial("~/Views/CategoryTree/ChildNode.cshtml", tNode.ChildNode)
                </div>
        </li>
        }
    </ul>
</div>
    </div>

<div id="formDiv" style="width:700px;float:left;margin-left: 50px;">
 
</div>
    </div>
<script type="text/javascript">
    $(function () {
        $("#tree").delegate( "span.arrowToggle", "click", function() {
            $(this).parent().addClass("ddActive");
            $(".ddActive > .toggleTxt").toggle();
            $(this).parent().removeClass("ddActive");
            $(this).parents().show();
            ($(this).text() === "+") ? $(this).text("-") : $(this).text("+");
            //var status = $(this).closest("div").is(':visible');
            //$(this).text(status ? "+" : "-");
        });
    });
</script>



ChildNode.chtml 

@model IEnumerable<Models.TreeViewNodeVM>
@foreach (var treeNode in Model)
{
<ul>
    @if (treeNode != null)
    {
        <li>
            <span class="arrowToggle">-</span>
            <a class="mainHead" onclick="onaclick(this.id)" id="@treeNode.Id"> @treeNode.NodeName</a>
            @if (treeNode.ChildNode.Count > 0)
            {
                <div class="toggleTxt">
                @Html.Partial("~/Views/CategoryTree/ChildNode.cshtml", treeNode.ChildNode)
                    </div>
            }
        </li>
    }
</ul>  
}
Controller Code
EmployeeManager _emp = new EmployeeManager();
        public ActionResult Index()
        {
            List<TreeViewNodeVM> treeView = _emp.GetTreeVeiwList();
            return View(treeView);
        }

        public PartialViewResult ChildNode()
        {
            return PartialView();
        }
        public PartialViewResult ShowCategoryForm(string id)
        {
            mMediaCategory objmMediaCategory = new mMediaCategory();
            TempData["MediaCategoryId"] = id;
            objmMediaCategory=GetMediaCategoryRecord(Convert.ToInt64(id), "");
            return PartialView("~/Views/CategoryTree/ShowCategoryForm.cshtml", objmMediaCategory);
        }
        public mMediaCategory GetMediaCategoryRecord(Int64 MediaCategoryId, string Title)
        {
            mMediaCategory model = new mMediaCategory();
            if (MediaCategoryId > 0)
            {
                var obj = GlobalService.GetMediaCategoryById(MediaCategoryId);
                var MediaCategoryPermissions = GlobalService.GetMediaCategoryPermissionsData(Convert.ToInt32(MediaCategoryId)).ToMap<BO_MediaCategoryPermissions, mMediaCategoryPermissions>();
                var gids = "";

                foreach (var item in MediaCategoryPermissions)
                {
                    if (string.IsNullOrEmpty(gids))
                    {
                        gids = item.GroupId.ToString();
                    }
                    else
                    {
                        gids += "," + item.GroupId;
                    }
                }
                model = obj.ToMap<BO_MediaCategory, mMediaCategory>();
                model.MediaCategoryPermissions = MediaCategoryPermissions;
                model.Id = obj.Id;
                model.Title = obj.Title;
                model.Descriptions = obj.Descriptions;
                model.Title_Sp = obj.Title_Sp;
                model.Descriptions_Sp = obj.Descriptions_Sp;
                model.MenuTitle = model.MenuTitle;
                model.ImagePhone = obj.PhoneImageUrl;
                model.ImageTablet = obj.TabletImageUrl;
                model.EditStatus = obj.EditStatus;
                model.CreatedBy = "1";
                model.ModifiedBy = "1";
                model.Language = "en-US";
                model.CreatedDate = DateTime.Now;
                model.ModifiedDate = DateTime.Now;
                model.GroupIds = gids;
                model.SelectedMediaTypes = GetSelectedMediaTypes(obj.MediaTypes);
                TempData.Keep();
            }
            else
            {
                model = new mMediaCategory();
                model.Title = Title;
            }
            return model;
        }
        public string UploadMediaCategoryImageForPhone(string phoneImageName, string oldImage)
        {
            string newphoneImageName = string.Empty;
            if (!string.IsNullOrEmpty(phoneImageName))
            {
                if (!string.IsNullOrEmpty(oldImage))
                {
                    MLBPAHelper.DeleteFile(Server.MapPath("~/assets/MediaCategory/") + oldImage);
                }
                newphoneImageName = Guid.NewGuid() + Path.GetExtension(phoneImageName);
                MLBPAHelper.MoveFile("~/Content/PhotoImageTemp/" + phoneImageName, Server.MapPath("~/assets/MediaCategory/"), newphoneImageName);
                return newphoneImageName;
            }
            else
            {
                return oldImage;
            }
        }
        public string UploadMediaCategoryImageForTablet(string tabletImageName, string oldImage)
        {
            string newphoneImageName = string.Empty;
            if (!string.IsNullOrEmpty(tabletImageName))
            {
                if (!string.IsNullOrEmpty(oldImage))
                {
                    MLBPAHelper.DeleteFile(Server.MapPath("~/assets/MediaCategory/") + oldImage);
                }
                newphoneImageName = Guid.NewGuid() + Path.GetExtension(tabletImageName);
                MLBPAHelper.MoveFile("~/Content/TabletImageTemp/" + tabletImageName, Server.MapPath("~/assets/MediaCategory/"), newphoneImageName);
                return newphoneImageName;
            }
            else
            {
                return oldImage;
            }
        }
        // POST: /MediaCategory/Create
        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(mMediaCategory model, FormCollection form)
        {
            ModelState.Remove("MediaCategoryPermissions");
            if (ModelState.IsValid)
            {
                try
                {
                    string phoneImage = form["hdnForPhoneImage"];
                    string tabletImage = form["hdnForTabletImage"];
                    int MediaCategoryId = Convert.ToInt32(TempData["MediaCategoryId"]);
                    BO_MediaCategory objBO_MediaCategory = new BO_MediaCategory();
                    objBO_MediaCategory.Id = MediaCategoryId;
                    objBO_MediaCategory.Title = model.Title;
                    objBO_MediaCategory.Descriptions = model.Descriptions;
                    objBO_MediaCategory.Title_Sp = model.Title;
                    objBO_MediaCategory.Descriptions_Sp = model.Descriptions;
                    objBO_MediaCategory.MenuTile = model.MenuTile;
                    objBO_MediaCategory.ParentCategory = model.ParentCategoryId;
                    objBO_MediaCategory.MediaTypes = String.Join(",", model.PostedMediaTypes.MediaTypesIds);
                    objBO_MediaCategory.PhoneImageUrl = model.ImagePhone;
                    objBO_MediaCategory.TabletImageUrl = model.ImageTablet;
                    objBO_MediaCategory.EditStatus = model.EditStatus;
                    objBO_MediaCategory.CreatedBy = "1";
                    objBO_MediaCategory.ModifiedBy = "1";
                    objBO_MediaCategory.Language = "en-US";
                    objBO_MediaCategory.CreatedDate = DateTime.Now;
                    objBO_MediaCategory.ModifiedDate = DateTime.Now;
                    objBO_MediaCategory.PhoneImageUrl = UploadMediaCategoryImageForPhone(phoneImage, model.ImagePhone);
                    objBO_MediaCategory.TabletImageUrl = UploadMediaCategoryImageForTablet(tabletImage, model.ImageTablet);
                    int MCId = GlobalService.AddEditMediaCategory(objBO_MediaCategory);
                    if (MCId != 1)
                        objBO_MediaCategory.Id = MCId;
                    else
                        objBO_MediaCategory.Id = MediaCategoryId;
                    GlobalService.AddMediaCategoryPermission(Convert.ToInt32(objBO_MediaCategory.Id), Convert.ToString(model.GroupIds));
                    TempData.Clear();
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View(model);
                }
            }
            else
            {
                return View(model);
            }
        }
        public IEnumerable<MediaTypes> GetSelectedMediaTypes(string MediaTypesId)
        {
            List<MediaTypes> objListMediaTypes = new List<MediaTypes>();
            foreach (string id in GetSelectedMediaTypesIds(MediaTypesId).ToList())
            {
                MediaTypes objMediaTypes = new MediaTypes();
                objMediaTypes = MediaTypesRepository.Get(Convert.ToInt32(id));
                objMediaTypes.IsSelected = true;
                objListMediaTypes.Add(objMediaTypes);
            }
            return objListMediaTypes;
        }
        public string[] GetSelectedMediaTypesIds(string mediatypesid)
        {
            if (!string.IsNullOrEmpty(mediatypesid))
            {
                return mediatypesid.Split(',');
            }
            else
            {
                return new string[0];
            }

        }

TreeViewNodeVM.cs

public class TreeViewNodeVM
    {
        public TreeViewNodeVM()
        {
            ChildNode = new List<TreeViewNodeVM>();
        }

        public Int64 Id { get; set; }
        public string Title { get; set; }
        public string NodeName
        {
            get { return GetNodeName(); }
        }
        public IList<TreeViewNodeVM> ChildNode { get; set; }

        public string GetNodeName()
        {
           return this.Title;
        }
    }
    public class EmployeeManager
    {
        public List<TreeViewNodeVM> GetTreeVeiwList()
        {
            List<TreeViewNodeVM> rootNode = GlobalService.GetMediaCategoryList().ToList().
                                            Where(m=>m.ParentCategory==0).ToList().ToMap<BO_MediaCategory,TreeViewNodeVM>();
            foreach (TreeViewNodeVM rn in rootNode)
            {
                BuildChildNode(rn);
            }

            return rootNode;
        }
        private void BuildChildNode(TreeViewNodeVM rootNode)
        {
            if (rootNode != null)
            {
                List<TreeViewNodeVM> chidNode = (from e1 in GlobalService.GetMediaCategoryList()
                                                 where e1.ParentCategory == rootNode.Id
                                                 select new TreeViewNodeVM()
                                                 {
                                                     Id = e1.Id,
                                                     Title = e1.Title
                                                 }).ToList<TreeViewNodeVM>();
                if (chidNode.Count > 0)
                {
                    foreach (var childRootNode in chidNode)
                    {
                        BuildChildNode(childRootNode);
                        rootNode.ChildNode.Add(childRootNode);
                    }
                }
            }
        }
    }


No comments:

Post a Comment