Sunday, 5 March 2017

Asset tracking 6, dropdownlist option, button enable, disable javascript DOM. controller create postback overload

dropdownlist options are filtered by other dropdownlist selected option

filter by asset type, 3 items left enabled in model dropdownlist


add manufacture filter, only one item left

when model item is selected, manufacture and asset type are automatically selected

click blank option in any filter dropdownlist to refresh all filter dropdownlists

dropdownlist refreshed

submit button is disabled when model is not selected

serial # is required, submit will stop if left empty

submit button click, controller overloaded create action receives data 

redirected to display, serial ccc item is created


//asset controller.cs
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 async Task<IActionResult> Index()
        {
            await Load_employees_from_HR();
            employees_from_HR.Add(new employee_dto { Id = "", name = "" });
            ViewBag.employee_viewbag = new SelectList(employees_from_HR.OrderBy(x => x.name), "Id", "name");

            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>>();
                }
            }

            //employees_from_HR.Add(new employee_dto { Id = "", name = "" });

            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");
        }


        [HttpPost]
        public ActionResult return_asset(string employee_id)
        {
            Manager.retun_asset(employee_id);

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

        // GET: Asset/Create
        public async Task<IActionResult> Create()
        {
            await Load_employees_from_HR();
            employees_from_HR.Add(new employee_dto { Id = "", name = "" });
            ViewBag.employee_viewbag = new SelectList(employees_from_HR.OrderBy(x => x.name), "Id", "name");

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

            var manufacture_list = Manager.get_manufacture();
            ViewBag.manfuacture_viewbag = new SelectList(manufacture_list.OrderBy(x => x.name), "id", "name");

            var model_list = Manager.get_model();
            ViewBag.model_viewbag = new SelectList(model_list.OrderBy(x => x.name), "id", "name");

            var assets = Manager.get_all();

            return View(assets);
        }

        // POST: Asset/Create
        [HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult Create(IFormCollection collection)
        {
            try
            {

                Manager.add_new(new asset_dto
                {
                    AssetTypeId = Convert.ToInt32(collection["asset_types_viewbag"]),
                    AssignedTo = collection["employee_viewbag"],
                    ManufacturerId = Convert.ToInt32(collection["manfuacture_viewbag"]),
                    ModelId=Convert.ToInt32(collection["model_viewbag"]),
                    SerialNumber = collection["serial"]
                });

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

    }
}

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

//view/asset/create.cshtml

@model IEnumerable<BLL.DTOs.asset_dto>

<h2><label id="title_label">Create new asset</label></h2>
<label id="status" class="text-danger"></label>

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

    var asset_list = [];

    $(document).ready(function () {

        @foreach (var item in Model)
        {
            <text>
        asset_list.push(new asset_class('@item.Id', '@item.AssetTypeId',
            '@item.ManufacturerId', '@item.ModelId', '@item.AssignedTo', '@item.SerialNumber'));
        </text>
        }

        @*change dropdownlist color*@
        document.getElementById("asset_types_viewbag").style.color = "yellow";
        document.getElementById("asset_types_viewbag").style.backgroundColor = "green";

        document.getElementById("manfuacture_viewbag").style.color = "yellow";
        document.getElementById("manfuacture_viewbag").style.backgroundColor = "green";

        document.getElementById("model_viewbag").style.color = "yellow";
        document.getElementById("model_viewbag").style.backgroundColor = "green";

        document.getElementById("employee_viewbag").style.color = "yellow";
        document.getElementById("employee_viewbag").style.backgroundColor = "green";

        //disable submit button
        document.getElementById("ux_submit").disabled = true;
    });

    function asset_class(id, asset_type_id, manufacture_id, model_id, employee_id, serial_number) {
        this.id = id;
        this.asset_type_id = asset_type_id;
        this.manufacture_id = manufacture_id;
        this.model_id = model_id;
        this.employee_id = employee_id;
        this.serial_number = serial_number;
    }

    function asset_type_onchange(){    

        //set manufacture and model dropdownlist selected value to "", if empty option is selected from asset_type_dropdownlist
        if ($("#asset_types_viewbag").val() == 0) {
            document.getElementById("manfuacture_viewbag").options[0].selected = true;
            document.getElementById("model_viewbag").options[0].selected = true;

            //enable all asset_type_dropdownlist option, if empty option is selected from asset_type_dropdownlist
            $("#asset_types_viewbag option").each(function (index, element) {

                document.getElementById("asset_types_viewbag").options[index].disabled = false;
            });
        }

        //disable options in manufacture dropdownlist
        $("#manfuacture_viewbag option").each(function (index, element) {

            document.getElementById("manfuacture_viewbag").options[index].disabled = true;
        });

        //disable options in model dropdownlist
        $("#model_viewbag option").each(function (index, element) {

            document.getElementById("model_viewbag").options[index].disabled = true;
        });

        //enable empty option selection, option for no filter
        document.getElementById("manfuacture_viewbag").options[0].disabled = false;
        document.getElementById("model_viewbag").options[0].disabled = false;

        //enable options in manufacture and model dropdownlist based on asset type
        $.each(asset_list, function (index, value) {

            if ($('#asset_types_viewbag').val() == value.asset_type_id || $('#asset_types_viewbag').val() == 0) {                                

                //find option in manufacture dropdownlist with id = manufacture_id of the filtered asset item, enable it
                //$("#manfuacture_viewbag").find('option[value*=' + value.manufacture_id + ']').prop('disabled', false);
                $("#manfuacture_viewbag option").each(function (index2, element) {

                    if (element.value == value.manufacture_id) {

                        document.getElementById("manfuacture_viewbag").options[index2].disabled = false;
                    }
                });              
            }

            //filter model dropdown list with both asset type and manufacture
            if (($('#manfuacture_viewbag').val() == value.manufacture_id || $('#manfuacture_viewbag').val() == 0) &&
                ($('#asset_types_viewbag').val() == value.asset_type_id || $('#asset_types_viewbag').val() == 0)) {

                //find option in model dropdownlist with id = model_id of the filtered asset item, enable it
                $("#model_viewbag option").each(function (index2, element) {

                    if (element.value == value.model_id) {

                        document.getElementById("model_viewbag").options[index2].disabled = false;
                    }
                });
            }

        });
    }

    function manufacture_onchange() {

        //set asset type and model dropdownlist selected value to "", if empty option is selected from manufacture dropdownlist
        if ($("#manfuacture_viewbag").val() == 0) {
            document.getElementById("asset_types_viewbag").options[0].selected = true;
            document.getElementById("model_viewbag").options[0].selected = true;

            //enable all manufacture_dropdownlist option, if empty option is selected from manufacture_dropdownlist
            $("#manfuacture_viewbag option").each(function (index, element) {

                document.getElementById("manfuacture_viewbag").options[index].disabled = false;
            });
        }

        //disable options in asset type dropdownlist
        $("#asset_types_viewbag option").each(function (index, element) {

            document.getElementById("asset_types_viewbag").options[element.value].disabled = true;
        });

        //disable options in model dropdownlist
        $("#model_viewbag option").each(function (index, element) {

            document.getElementById("model_viewbag").options[element.value].disabled = true;
        });

        //enable empty option selection, option for no filter
        document.getElementById("asset_types_viewbag").options[0].disabled = false;
        document.getElementById("model_viewbag").options[0].disabled = false;

        //enable options in asset type and model dropdownlist based on manufacture
        $.each(asset_list, function (index, value) {

            if ($('#manfuacture_viewbag').val() == value.manufacture_id || $('#manfuacture_viewbag').val() == 0) {              

                //find option in asset type dropdownlist with id = asset_type_id of the filtered asset item, enable it
                $("#asset_types_viewbag option").each(function (index2, element) {

                    if (element.value == value.asset_type_id) {

                        document.getElementById("asset_types_viewbag").options[index2].disabled = false;
                    }
                });
            }

            //filter model dropdown list with both asset type and manufacture
            if (($('#manfuacture_viewbag').val() == value.manufacture_id || $('#manfuacture_viewbag').val() == 0)&&
                ($('#asset_types_viewbag').val() == value.asset_type_id || $('#asset_types_viewbag').val() == 0)) {

                //find option in model dropdownlist with id = model_id of the filtered asset item, enable it
                $("#model_viewbag option").each(function (index2, element) {

                    if (element.value == value.model_id) {

                        document.getElementById("model_viewbag").options[index2].disabled = false;
                    }
                });
            }
        });
   
    }

    function model_onchange() {

        //disable submit button
        document.getElementById("ux_submit").disabled = true;

        //set asset type and manufacture dropdownlist selected value to "", if empty option is selected from model dropdownlist
        if ($("#model_viewbag").val() == 0) {
            document.getElementById("asset_types_viewbag").options[0].selected = true;
            document.getElementById("manfuacture_viewbag").options[0].selected = true;

            //enable all dropdownlist option, if empty option is selected from manufacture_dropdownlist
            $("#manfuacture_viewbag option").each(function (index, element) {

                document.getElementById("manfuacture_viewbag").options[index].disabled = false;
            });

            $("#asset_types_viewbag option").each(function (index, element) {

                document.getElementById("asset_types_viewbag").options[index].disabled = false;
            });

            $("#model_viewbag option").each(function (index, element) {

                document.getElementById("model_viewbag").options[index].disabled = false;
            });

            return;
        }

        //disable options in asset type dropdownlist
        $("#asset_types_viewbag option").each(function (index, element) {

            document.getElementById("asset_types_viewbag").options[element.value].disabled = true;
        });

        //disable options in manufacture dropdownlist
        $("#manfuacture_viewbag option").each(function (index, element) {

            document.getElementById("manfuacture_viewbag").options[element.value].disabled = true;
        });

        //enable empty option selection, option for no filter
        document.getElementById("asset_types_viewbag").options[0].disabled = false;
        document.getElementById("manfuacture_viewbag").options[0].disabled = false;

        //select options in asset type and manufacture dropdownlist based on model
        $.each(asset_list, function (index, value) {

            if ($('#model_viewbag').val() == value.model_id) {

                //select asset type
                $("#asset_types_viewbag option").each(function (index2, element) {

                    if (element.value == value.asset_type_id) {

                        document.getElementById("asset_types_viewbag").options[index2].disabled = false;
                        document.getElementById("asset_types_viewbag").options[index2].selected = true;
                    }
                });

                //select manufacture type
                $("#manfuacture_viewbag option").each(function (index2, element) {

                    if (element.value == value.manufacture_id) {

                        document.getElementById("manfuacture_viewbag").options[index2].disabled = false;
                        document.getElementById("manfuacture_viewbag").options[index2].selected = true;
                    }
                });
            }
        });

        //if model dropdownlist selected option is not "", enable submit button
        if ($('#model_viewbag').val() != 0) {
            document.getElementById("ux_submit").disabled = false;
        }
    }  

   
</script>


<form id="create_form" method="post" onsubmit="return check_model_selct()">

    <div class="col-md-2">
        @Html.Label("Asset type")
        @Html.DropDownList("asset_types_viewbag", null, htmlAttributes: new { @class = "form-control", onchange = "asset_type_onchange()" })
    </div>

    <div class="col-md-2">
        @Html.Label("Manufacture")
        @Html.DropDownList("manfuacture_viewbag", null, htmlAttributes: new { @class = "form-control", onchange = "manufacture_onchange()" })
    </div>

    <div class="col-md-2">
        @Html.Label("Model")
        @Html.DropDownList("model_viewbag", null, htmlAttributes: new { @class = "form-control", onchange = "model_onchange()" })
    </div>

    <div class="col-md-2">
        @Html.Label("Employee")
        @Html.DropDownList("employee_viewbag", null, htmlAttributes: new { @class = "form-control" })
    </div>

    <div class="col-md-2">
        @Html.Label("Serial #")
        @Html.TextBox("serial",null, htmlAttributes: new { @class = "form-control", required = "required" })
    </div>

    <div class="col-md-2">
        @Html.Label("Select model and input serail # first")
        <input id="ux_submit" type="submit" value="submit" class="form-control" />
    </div>

</form>

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

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,

                ////try to find manufacture_id from DB.Asset, if not found, try DB.Models, not found 0
                ManufacturerId = x.ManufacturerId.HasValue ? (int)x.ManufacturerId : (x.ModelId.HasValue?
                (int)DB.Models.FirstOrDefault(y=>y.Id==x.ModelId).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;
        }

        public void retun_asset(string employee_id)
        {
            foreach(var item in DB.Assets)
            {
                if(item.AssignedTo==employee_id)
                {
                    item.AssignedTo = "";
                }
            }
            DB.SaveChanges();
        }

        public IList<manufacture_dto> get_manufacture()
        {
            var manufactures = DB.Manufacturers.Select(x => new manufacture_dto
            {
                id = x.Id,
                name = x.Name

            }).ToList();

            manufactures.Add(new manufacture_dto { id = 0, name = "" });

            return manufactures;
        }

        public IList<model_dto> get_model()
        {
            var models = DB.Models.Select(x => new model_dto
            {
                id = x.Id,
                manufacture_id = (int)x.ManufacturerId,
                name = x.Name
            }).ToList();

            models.Add(new model_dto { id = 0, manufacture_id = 0, name = "" });

            return models;
        }

        public void add_new(asset_dto new_item)
        {
            DB.Assets.Add(new Domain.Asset
            {
                AssetTypeId = new_item.AssetTypeId,
                ManufacturerId = new_item.ManufacturerId,
                ModelId = new_item.ModelId,
                AssignedTo = new_item.AssignedTo,
                SerialNumber=new_item.SerialNumber
            });

            DB.SaveChanges();
        }
    }
}

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

//BLL/DTOs/model.dto

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

namespace BLL.DTOs
{
    public class model_dto
    {
        public int id { get; set; }
        public int manufacture_id { get; set; }
        public string name { get; set; }
    }
}

1 comment:

  1. Wonderful blog & good post.Its really helpful for me, Your blog is easily understandable and give complete information. Keep sharing new ideas and features.
    Asset Management Software
    Asset Tracking Software
    Asset Management Software India
    Asset Management Software Chennai

    ReplyDelete