Select with optgroup via ajax and mvc controller

I had a need to bind a select control to a set of json data delievered via a  $ ajax call…

 

C# method

 public List<SelectListItem> changeHistorySelect { get; private set; }

        [AcceptVerbs(HttpVerbs.Get)]

        public ActionResult GetChangeHistorySelect(Int64 Id)
        {
            var selectListGroup_Info = new SelectListGroup() { Name = "Info"};
            var selectListGroup_Allotments = new SelectListGroup() { Name = "Allotments" };
            var selectListGroup_Financial = new SelectListGroup() { Name = "Financial" };
            var selectListGroup_Daily_Status = new SelectListGroup() { Name = "Daily Status" };
            var selectListGroup_Enrollments = new SelectListGroup() { Name = "Enrollments" };

            #region  Misc Code...

            // Build list
            changeHistorySelect = new List<SelectListItem>
            {
              new  SelectListItem
              {
                  Value = "",
                  Text = "- Select -",
                  Selected = true
                 
              },
                new SelectListItem
                {
                    Value = "student",
                    Text = "Student",
                    Group = selectListGroup_Info
                },
                new SelectListItem
                {
                    Value = "altAddresses",
                    Text = "Alternate Addresses",
                    Group = selectListGroup_Info
                },
                new SelectListItem
                {
                    Value = "enrollment",
                    Text = "Enrollment",
                    Group = selectListGroup_Info
                },
                new SelectListItem
                {
                    Value = "enrollmentType",
                    Text = "Enrollment Type",
                    Group = selectListGroup_Info
                },


                new SelectListItem
                {
                    Value = "allotteeInfo",
                    Text = "Allottee Information",
                    Group = selectListGroup_Allotments
                },

                new SelectListItem
                {
                    Value = "earnings",
                    Text = "Earnings",
                    Group = selectListGroup_Financial
                },
                new SelectListItem
                {
                    Value = "deductions",
                    Text = "Deductions",
                    Group = selectListGroup_Financial
                },
                new SelectListItem
                {
                    Value = "reimbursements",
                    Text = "Reimbursements",
                    Group = selectListGroup_Financial
                },
                new SelectListItem
                {
                    Value = "accruals",
                    Text = "Accruals",
                    Group = selectListGroup_Financial
                },
              
            };

            // Now add enrollments to list

            var enrollments = new StudentChangeHistoryService().GetStudentEnrollment(Id);
            foreach (var er in enrollments)
            {
                if (er.sep_dt.ToString() == "1/1/0001 12:00:00 AM")
                {
                    changeHistorySelect.Add(new SelectListItem
                    {
                        Value = er.enr_dt != null ? er.enr_dt.Value.ToString("MM/dd/yyyy") : String.Empty,
                        Text = "Current Enrollment: " + (er.enr_dt != null ? er.enr_dt.Value.ToString("MM/dd/yyyy") : String.Empty) + " - Current",
                        Group = selectListGroup_Daily_Status
                    });
                }
                else
                {
                    changeHistorySelect.Add(new SelectListItem
                    {
                        Value = er.enr_dt != null ? er.enr_dt.Value.ToString("MM/dd/yyyy") : String.Empty,
                        Text = String.Format("Prior Enrollment: {0} - {1} ", er.enr_dt != null ? er.enr_dt.Value.ToString("MM/dd/yyyy") : String.Empty,(er.sep_dt != null ? er.sep_dt.Value.ToString("MM/dd/yyyy"): String.Empty)), 
                        Group = selectListGroup_Daily_Status
                    });
                }


            }

            var jsonResult = Json(changeHistorySelect);
            #endregion

            return Json(changeHistorySelect,JsonRequestBehavior.AllowGet);
        }

Now I need to have the UI call and build selector in javascript


 function getChangeHistorySelect(studentId) {

            $.getJSON('@Url.Action("GetChangeHistorySelect")', { Id: studentId }).done(function (data) {

                console.log(data);
                var result = data;

                var changeHistorySelect = $('#changeHistorySelect');
                changeHistorySelect.empty();
                var groupName = '';
                var groupPreviousName = '';
                $.each(result,
                    function () {
                        // Need an outloop for the option group
                       // debugger;
                        if (this.Group != null) {
                            // Has the group already been added?
                            var group = this.Group;
                            if (groupName === '') {

                                groupName = group.Name;
                                groupPreviousName = groupName;
                                // First Add...
                                changeHistorySelect.append(
                                    $('<optgroup>',
                                        {
                                            label: groupName,
                                            id: groupName
                                        }));


                            } else {
                                groupName = group.Name;
                                // A group has already been added... does it match?
                                if (groupPreviousName === groupName) {
                                    // They Match skip (added select under this group
                                } else {
                                    // They don' match, add new optGroup and contiue on to add selects under it
                                    groupName = group.Name;
                                    groupPreviousName = groupName;

                                    changeHistorySelect.append(
                                        $('<optgroup>',
                                            {
                                                label: groupName,
                                                id: groupName.replace(/\s/g, "")
                                            }));
                                }
                            }
                            // Add Option Group
                            var custom = $('#' + groupName.replace(/\s/g, ""));
                            var option = $("<option></option>");
                            option.val(this.Value);
                            option.text(this.Text);
                            option.appendTo(custom);


                        } else {
                            changeHistorySelect.append(
                                                           $('<option>',
                                                               {
                                                                   value: this.Value
                                                               }).text(this.Text)
                                                       );
                        }

                    });

            });
        }


.

 

 

 

 

 

 

Visual Studio 2017 JQuery, WebPack and .Core

http://leruplund.dk/2017/04/15/setting-up-asp-net-core-in-visual-studio-2017-with-npm-webpack-and-typescript-part-i/

 

The CLI moved into a separate package: webpack-cli.
Please install ‘webpack-cli’ in addition to webpack itself to use the CLI.
-> When using npm: npm install webpack-cli -D
-> When using yarn: yarn add webpack-cli -D

https://github.com/FormidableLabs/webpack-dashboard/issues/97

 

(Make sure you deleted the bundle.js file to ensure your task runner is executing correctly)

If you configure the TASK RUNNER EXPLORER and you do NOT get your files in the DIST FOLDER…
Make sure that Visual Studio is using the global installed version of npm not it’s local.
In VS 2017 TOOLS | OPTIONS
In filter box type: External Web Tools

Move $(PATH) to the top of the list in the Locations of External tool

 

npm install jquery –save

Adding JQuery typings

https://www.npmjs.com/package/@types/jquery

Install d3 via npm then typings

npm install –save d3

npm install –save @types/d3

Useful Tools for Development and UI stuff

Chrome Extensions

Photo by Caio Resende from Pexels

Now that I am a self-proclaimed web developer, I practically live in my Chrome console. Below are some tools that allow me to spend less time there:

  • WhatFont — The name says it all. This is an easy way of finding out the fonts that your favorite website is using, so that you can borrow them for your own projects.
  • Pesticide — Useful for seeing the outlines of your <div>s and modifying CSS. This was a lifesaver when I was trying to learn my way around the box-model.
  • Colorzilla — Useful for copying exact colors off of a website. This copies a color straight to your clipboard so you don’t spend forever trying to get the right RGBA combination.
  • CSS Peeper — Useful for looking at colors and assets used on a website. A good exercise, especially when starting out, is cloning out websites that you think look cool. This gives you a peek under the hood at their color scheme and allows you to see what other assets exist on their page.
  • Wappalyzer — Useful for seeing the technologies being used on a website. Ever wonder what kind of framework a website is using or what service it is hosted on? Look no further.
  • React Dev Tools — Useful for debugging your React applications. It bears mentioning that this is only useful if you are programming a React application.
  • Redux Dev Tools — Useful for debugging applications using Redux. It bears mentioning that this is only useful if you are implementing Redux in your application.
  • JSON Formatter — Useful for making JSON look cleaner in the browser. Have you ever stared an ugly JSON blob in the face, trying to figure out how deeply nested the information you want is? Well this makes it so that it only takes 2 hours instead of 3.
  • Vimeo Repeat and Speed — Useful for speeding up Vimeo videos. If you watch video tutorials like most web developers, you know how handy it is to consume them at 1.25 times the regular playback speed. There are also versions for YouTube.

VS Code Extensions

Photo Courtesy of Pexels

Visual Studio Code is my editor of choice.

People love their text editors, and I am no exception. However, I’m willing to bet most of these extensions work for whatever editor you are using as well. Check out my favorite extensions:

  • Auto Rename Tag — Auto rename paired HTML tags. You created a <p>tag. Now you want to change it, as well as its enclosing </p> tag to something else. Simply change one and the other will follow. Theoretically improves your productivity by a factor of 2.
  • HTML CSS Support — CSS support for HTML documents. This is useful for getting some neat syntax highlighting and code suggestions so that CSS only makes you want to quit coding a couple of times a day.
  • HTML Snippets — Useful code snippets. Another nice time saver. Pair this with Emmet and you barely ever have to type real HTML again.
  • Babel ES6/ES7 — Adds JavaScript Babel syntax coloring. If you are using Babel, this will make it much easier to differentiate what is going on in your code. This is neat if you like to play with modern features of JavaScript.
  • Bracket Pair Colorizer — Adds colors to brackets for easier block visualization. This is handy for those all-too-common bugs where you didn’t close your brackets or parentheses accurately.
  • ESLint — Integrates ESLint into Visual Studio Code. This is handy for getting hints about bugs as you are writing your code and, depending on your configuration, it can help enforce good coding style.
  • Guides — Adds extra guide lines to code. This is another visual cue to make sure that you are closing your brackets correctly. If you can’t tell, I’m a very visual person.
  • JavaScript Console Utils — Makes for easier console logging. If you are like most developers, you will find yourself logging to the console in your debugging flow (I know that we are supposed to use the debugger). This utility makes it easy to create useful console.log() statements.
  • Code Spell Checker — Spelling checker that accounts for camelCase. Another common source of bugs is fat-thumbing a variable or function name. This spell checker will look for uncommon words and is good about accounting for the way we write things in JavaScript.
  • Git Lens — Makes it easier to see when, and by whom, changes were made. This is nice for blaming the appropriate person when code gets broken, since it is absolutely never your fault.
  • Path Intellisense — File path autocompletion. This is super handy for importing things from other files. It makes navigating your file tree a breeze.
  • Prettier — Automatic code formatter. Forget about the days where you had to manually indent your code and make things human-legible. Prettier will do this for you much faster, and better, than you ever could on your own. I can’t recommend this one enough.
  • VSCode-Icons — Adds icons to the file tree. If looking at your file structure hurts your eyes, this might help. There is a helpful icon for just about any kind of file you are making which will make it easier to distinguish what you are looking at.

 

SOURCE:  https://medium.freecodecamp.org/tools-i-wish-i-had-known-about-when-i-started-coding-57849efd9248

%d bloggers like this: