Tuesday, 28 February 2017

AssetTracking 5, client side: jquery 2 listbox exchange items, Ajax send obj to controller. server sdie: async controller action



click assign asset menu, list unassigned employee, assets

select multiple asset, click unassigned asset, goes to selected asset, vice-versa

assets can be filtered, if employee or asset is not selected, alert, otherwise assign

employee with id SM1003 is assigned multiple assets

//asset controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using BLL;
using Data;
using Microsoft.AspNetCore.Mvc.Rendering;
using BLL.DTOs;
using System.Net.Http;
using System.Net.Http.Headers;

namespace AssetTracking.Controllers
{
    public class AssetController : Controller
    {
        asset_manager Manager;
        List<employee_dto> employees_from_HR;

        public AssetController(AssetContext context)
        {
            Manager = new asset_manager(context);        
        }    

        // GET: Asset
        public ActionResult Index()
        {
            var asset_types_list = Manager.get_asset_types();

            ViewBag.asset_types_viewbag = new SelectList(asset_types_list.OrderBy(x=>x.Name), "Id", "Name");

            var assets = Manager.get_all();

            return View(assets);
        }

        public async Task<IActionResult> Assign()
        {
         
            await Load_employees_from_HR();
            var employee_without_asset = Manager.find_employees_without_asset(employees_from_HR);

            var asset_types_list = Manager.get_asset_types();
            ViewBag.asset_types_viewbag = new SelectList(asset_types_list.OrderBy(x => x.Name), "Id", "Name");

            var unassigned_asset = Manager.get_unassigned_assets();
            ViewBag.unassigned_asset =unassigned_asset.OrderBy(x => x.name);
                     

            return View(employee_without_asset);
        }

        public async Task<IActionResult> Load_employees_from_HR()
        {
            employees_from_HR = new List<employee_dto>();
            //make call to web api
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:11111/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.
                    Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync("api/values");
                if (response.IsSuccessStatusCode)
                {
                    employees_from_HR = await response.Content.ReadAsAsync<List<employee_dto>>();
                }
            }

            return Content("employees are loaded from HR");
        }

        [HttpPost]
        public ActionResult update_assignment(List<asset_assign_class> assignment)
        {
            Manager.assign_asset(assignment);

            //redirect to Index is handled by Ajax on success event in Assign View 
            return Content("assignment success");
        }
}

---------------------------------------------------------------------------------------------------

//manager

using Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BLL.DTOs;
using System.Net.Http;
using System.Net.Http.Headers;

namespace BLL
{

    public class asset_manager
    {
        AssetContext DB;

        public asset_manager(AssetContext context)
        {
            DB = context;
        }

        public IList<asset_dto> get_all()
        {
            return DB.Assets.Select(x => new asset_dto
            {

                Id = x.Id,
                AssignedTo = x.AssignedTo,
                Description = x.Description,
                SerialNumber = x.SerialNumber,
                TagNumber = x.TagNumber,

                AssetTypeId = x.AssetTypeId.HasValue ? (int)x.AssetTypeId : 0,
                ManufacturerId = x.ManufacturerId.HasValue ? (int)x.ManufacturerId : 0,
                ModelId = x.ModelId.HasValue ? (int)x.ModelId : 0,

                AssetType = x.AssetTypeId.HasValue ? DB.AssetType.FirstOrDefault(y => y.Id == x.AssetTypeId).Name : "",
                Model = x.ModelId.HasValue ? DB.Models.FirstOrDefault(y => y.Id == x.ModelId).Name : "",

                //try to find manufacture from DB.Asset, if not found, try DB.Models, not found ""
                Manufacturer = x.ManufacturerId.HasValue ? DB.Manufacturers.FirstOrDefault(y => y.Id == x.ManufacturerId).Name :
                (x.ModelId.HasValue ? DB.Manufacturers.FirstOrDefault(M => M.Id ==
                DB.Models.FirstOrDefault(z => z.Id == x.ModelId).ManufacturerId).Name : "")

            }).ToList();
        }    

        public IList<asset_short_dto> get_unassigned_assets()
        {
            return DB.Assets.Where(y=>y.AssignedTo==""||y.AssignedTo==null).
                Select(x => new asset_short_dto{
                    Id = x.Id,
                    name = x.ModelId.HasValue ? DB.Models.FirstOrDefault(z => z.Id == x.ModelId).Name : "",
                    type_id = x.AssetTypeId.HasValue ? (int)x.AssetTypeId : 0
                }).ToList();

        }

        public IList<asset_type_dto> get_asset_types()
        {
            var asset_types =  DB.AssetType.Select(x=> new asset_type_dto
            {
                Id=x.Id,
                Name=x.Name

            }).ToList();

            asset_types.Add(new asset_type_dto { Id = 0, Name = "" });

            return asset_types;
        }

        public void assign_asset(List<asset_assign_class> assignment)
        {
            foreach(var item in assignment)
            {
                DB.Assets.FirstOrDefault(x => x.Id == item.id).AssignedTo = item.employee_id;
                DB.SaveChanges();
            }
        }

        public IList<employee_dto> find_employees_without_asset(List<employee_dto> employees)
        {
            foreach(var item in DB.Assets)
            {
                if(item.AssignedTo!="")
                {
                    var employee_with_asset = employees.FirstOrDefault(x => x.Id == item.AssignedTo);

                    if (employee_with_asset != null)
                    {
                        employees.Remove(employee_with_asset);
                    }
                }
            }

            return employees;
        }
    }
}

--------------------------------------------------------------------------

//View

@model IEnumerable<BLL.DTOs.employee_dto>

<h2>Asset Assignment</h2>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">

    var employee_list = [];
    var unassigned_asset_list = []
    var selected_asset_list = []
    var assignment_list = []

    $(document).ready(function () {

        //populate unassigned employee listbox
        @foreach (var item in Model)
        {
            <text>
        employee_list.push(new employee_class('@item.Id', '@item.name'));
        </text>
        }

        populate_employee();

        //populate unassigned assets listbox
        @foreach (var item in ViewBag.unassigned_asset)
        {
            <text>
        unassigned_asset_list.push(new asset_class('@item.Id', '@item.name', '@item.type_id'));
        </text>
        }

        populate_asset();
    });

    function employee_class(id, name) {
        this.id = id;
        this.name = name;
    }

    function asset_class(id, name, type) {
        this.id = id;
        this.name = name;
        this.type = type;
    }

    function assignment_class(id, employee_id) {

        this.id = id;
        this.employee_id = employee_id;
    }

    //delete element from array
    function array_delete(array, element_id) {

        //find index of the element going to be deleted in the arry
        indexes = $.map(array, function (obj, index) {

            if (element_id == obj.id) {

                return index;
            }
        })

        //return deleted element as asset class
        deleted_item = array.splice(indexes[0], 1);

        return new asset_class(deleted_item[0].id, deleted_item[0].name, deleted_item[0].type);
    }

    function populate_employee() {

        $.each(employee_list, function (index, value) {
            $('#ux_employee_unassigned').append('<option value=' + value.id + '>' + value.name + '</option>');
        });
    }

    //populate unassigned asset listbox
    function populate_asset() {

        $.each(unassigned_asset_list, function (index, value) {
            $('#ux_unassigned_asset').append('<option value=' + value.id + '>' + value.name + '</option>');
        });
    }

    //populate unassigned asset listbox based on type
    function populate_asset_baseon_type(_type) {

        $.each(unassigned_asset_list, function (index, value) {

            if (value.type == _type) {
                $('#ux_unassigned_asset').append('<option value=' + value.id + '>' + value.name + '</option>');
            }
        })
    }

    //populate selected asset listbox
    function populate_asset_selected() {      

        $.each(selected_asset_list, function (index, value) {
            $('#ux_selected_asset_listbox').append('<option value=' + value.id + '>' + value.name + '</option>');
        });
    }

    //populate selected asset listbox based on type
    function populate_asset_selected_basedon_type(_type) {

        $.each(selected_asset_list, function (index, value) {

            if (value.type == _type) {
                $('#ux_selected_asset_listbox').append('<option value=' + value.id + '>' + value.name + '</option>');
            }
        });
    }

    //asset type dropdownlist change event
    function asset_types_onchange() {

        $('#ux_unassigned_asset').empty();
        $('#ux_selected_asset_listbox').empty();

        //if selected type = "", populate with all assets
        if ($('#asset_types_viewbag :selected').text() == "") {
            populate_asset();
            populate_asset_selected();
        }
            //populate unassigned assets listbox based on asset type
        else {
            populate_asset_baseon_type($('#asset_types_viewbag').val());
            populate_asset_selected_basedon_type($('#asset_types_viewbag').val());
        }
    }

    //unassigned asset listbox onselect event, move asset to selected listbox
    function unassigned_asset_listbox_onchange() {

        //delete selected item from uassigned_asset_listbox
        deleted_element = array_delete(unassigned_asset_list, $("#ux_unassigned_asset").val());

        //add selected item to selected_asset_listbox
        selected_asset_list.push(deleted_element);

        //sort selectd asset list
        selected_asset_list.sort(function (a, b) {

            var aName = a.name.toLowerCase();
            var bName = b.name.toLowerCase();
            return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        });

        //repopulate unassigned_asset_listbox
        asset_types_onchange();        
    }


    //selected asset listbox onselect event, return asset to unassigned listbox
    function selected_asset_listbox_onchange() {

        //delete selected item from selected asset listbox
        deleted_element = array_delete(selected_asset_list, $("#ux_selected_asset_listbox").val());

        //add selected item to unassigned asset listbox
        unassigned_asset_list.push(deleted_element);

        //sort unassigned asset list
        unassigned_asset_list.sort(function (a, b) {

            var aName = a.name.toLowerCase();
            var bName = b.name.toLowerCase();
            return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
        });

        //repopulate unassigned_asset_listbox and selected_asset_listbox
        asset_types_onchange();
    }

    //confirm button click event
    function button_confirm() {

        if ($('#ux_employee_unassigned').val() == undefined) { alert("please select employee"); return }

        if (selected_asset_list.length == 0) { alert("please select asset"); return}

        //create asset assignment to selected employee
        $.each(selected_asset_list, function (index, value) {

            assignment_list.push(new assignment_class(value.id, $('#ux_employee_unassigned').val()));
        })

        //send assignment to controller
        $.ajax({
            type: "POST",
            url: '/Asset/update_assignment',
            data: { "assignment": assignment_list },
            success: function (result) {
                //alert("success");
                window.location.replace("/Asset/Index");
            },
            error: function (xhr) {
                alert("Error button confirm Assign view");
            }
        });
    };
</script>

<div>
    <div class="col-md-3">

        <center>@Html.Label("select unassigned employee")</center>
        <select size="20" id="ux_employee_unassigned" class="form-control"></select>
    </div>

    <div class="col-md-6">

        <center> @Html.Label("select asset type")</center>
        <center> @Html.DropDownList("asset_types_viewbag", null, htmlAttributes: new { @class = "form-control", onchange = "asset_types_onchange()" })</center> 
        <br />

        <div class="row">
            <div class="col-md-6">

                <center>  @Html.Label("select unassigned asset")</center>
                <select size="15" id="ux_unassigned_asset" class="form-control" onchange="unassigned_asset_listbox_onchange()"></select>
            </div>

            <div class="col-md-6">

                <center> @Html.Label("return selected asset")</center>

                <select size="15" id="ux_selected_asset_listbox" class="form-control" onchange="selected_asset_listbox_onchange()"></select>
            </div>
        </div>
  
    </div>

    <div class="col-md-3">
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <center> <button onclick="button_confirm()" type="button" class="btn btn-success">Assign selected assets<br />to selected employee</button></center>
        <br />
        <br />
        <br />
        <br />
        <center> <button onclick="button_cancel()" type="button" class="btn btn-danger">Cancel assignment</button></center>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
       
    </div>
    
</div>

---------------------------------------------------------------------

//asset_assign_class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BLL.DTOs
{
    public class asset_assign_class
    {
        public int id { get; set; }
        public string employee_id { get; set; }
    }
}


reference:
http://stackoverflow.com/questions/12944329/add-onclick-function-to-a-submit-button
http://stackoverflow.com/questions/8893111/how-do-i-disable-input-element-whose-type-is-submit
https://www.w3schools.com/tags/att_input_required.asp
http://stackoverflow.com/questions/1594952/jquery-disable-enable-submit-button
http://stackoverflow.com/questions/2950152/iterate-through-select-options
https://www.w3schools.com/jsref/prop_option_disabled.asp
http://stackoverflow.com/questions/40422727/disable-drop-down-options-based-on-selected-value-with-jquery
http://stackoverflow.com/questions/1263852/prevent-form-redirect-or-refresh-on-submit
http://stackoverflow.com/questions/12944329/add-onclick-function-to-a-submit-button
http://stackoverflow.com/questions/23071795/how-to-add-required-attribute-to-mvc-5-razor-view-text-input-editor

No comments:

Post a Comment