MVC 3.5 Helper

Org: https://docs.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/creating-and-using-a-helper-in-an-aspnet-web-pages-site

Using the Helper in a Page

  1. In the root folder, create a new blank file called TestHelper.cshtml.
  2. Add the following code to the file:
    HTMLCopy
    <!DOCTYPE html>
      <head>
        <title>Test Helpers Page</title>
      </head>
      <body>
        <p>This is some opening paragraph text.</p>
    
        <!-- Insert the call to your note helper here. -->
        @MyHelpers.MakeNote("My test note content.")
    
        <p>This is some following text.</p>
      </body>
    </html>
    

    To call the helper you created, use @ followed by the file name where the helper is, a dot, and then the helper name. (If you had multiple folders in the App_Code folder, you could use the syntax @FolderName.FileName.HelperName to call your helper within any nested folder level). The text that you add in quotation marks within the parentheses is the text that the helper will display as part of the note in the web page.

  3. Save the page and run it in a browser. The helper generates the note item right where you called the helper: between the two paragraphs.

    Screenshot showing the page in the browser and how the helper generated markup that puts a box around the specified text.

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

                    });

            });
        }


.

 

 

 

 

 

 

DATEDIFF two dates 1 year apart

For a friend who needed to know how to check if two dates in Sybase ASE 12 are a year apart.

A JavaScript Solution

Add moment.js lib

// TODO: Validate if date diff is no more than 1 year
var startSepDt = moment($('#startDateSep').val());
var endSepDt = moment($('#sendDateSep').val());
var dateDiff = endSepDt.diff(startSepDt, 'year');
if (dateDiff > 1) 
{
       showInValidSeasrchWarning('The date range cannot exceed a year.');
       return false;
}

 

A SQL Solution

-- DATEDIFF two dates 1 year apart
DECLARE @year1 datetime, @year2 datetime
SET @year1 = DATEADD(year,-1,GetDate())
SET @year2 = GetDate()
SELeCT @year1, @year2, datediff(year,@year1,@year2) 
if( datediff(year,@year1,@year2) <= 1 AND datediff(dd,@year1, @year2) <= 365 )
print 'Hurray! Within one year..'
else
print ':( Difference is more than a year'
%d bloggers like this: