Wednesday, October 2, 2013

Create Custom Calendar in MVC

There are several plugins out there that can help you to create a calendar in MVC, JQuery, and other languages, but one disadvantage to all of these is a lack of customization.  In searching the web, I noticed that not many articles have been written about this topic, so here's one example.

This article will help you get started in creating a fully customizable HtmlHelper method to use throughout your application in MVC.  I prefer MVC4, but it will work with version 3 as well.

First, create a static class and name it whatever.  Mine is called DataControls, but it isn't important.  The only reason for the static method is so that you can use it as an MVC helper class in your view.

The class looks like this:

using System;
using System.Globalization;
using System.Text;
using System.Web.Mvc;
public static class DataControls
    {
        public enum DayFormat
        {
            Long, Medium, Short
        }

        public static MvcHtmlString Calendar(
  this HtmlHelper helper,
  DayFormat dayFormat,
  int month, int year)
        {
            DateTime today = DateTime.Now;
            int daysInMonth = DateTime.DaysInMonth(year, month);
            string[] dayNames = new string[] { };
            switch (dayFormat)
            {
                case DayFormat.Medium:
                    dayNames = new string[] { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
                    break;
                case DayFormat.Short:
                    dayNames = new string[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" };
                    break;
                case DayFormat.Long:
                    dayNames = new string[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
                    break;
                default:
                    throw new Exception("Please specify a Day Format.");
            }
            StringBuilder calendar = new StringBuilder();
            calendar.Append(string.Format("

", "calendar"));

            calendar.Append("");
            calendar.Append(" ");
            for (int i = 0; i < dayNames.Length; i++)
            {
                calendar.Append(string.Format("{0}", dayNames[i]));
            }
            calendar.Append("
");            calendar.Append("
");            calendar.Append("");
            for (int i = 1; i <= 42; i++)
            {
                if (i % 7 == 1)
                {
                    calendar.Append(" ");
                }
                calendar.Append("");
                DateTime firstDay = new DateTime(year, month, 1);
                int firstDayOfWeek = (int)CultureInfo
        .InvariantCulture.Calendar.GetDayOfWeek(firstDay);
                if (i > firstDayOfWeek && (i - firstDayOfWeek) <= daysInMonth)
                {
                    calendar.Append(i - firstDayOfWeek);
                }
                calendar.Append("
");                if (i % 7 == 7)
                {
                    calendar.Append("
");                }
            }
            calendar.Append("
");            calendar.Append("
");            return MvcHtmlString.Create(calendar.ToString());
        }
    }

In a nutshell, we are creating a table that allows us to specify a format for month names, and then doing a loop to determine what day of week each day falls on, as well as how many days occur in the selected month and year.  If you don't care about the format of the days, you don't have to use the enum, but I like to allow for customization.

Once this is created, you can simply call this function inside of your razor view by calling:

(This would generate a calendar for January of 2013)
@Html.Calendar(DataControls.DayFormat.Medium, 1, 2013)

Obviously, you'd want to create a filter mechanism for displaying months and years to the user so they could select a month and year, but that is outside of the scope of this article.  Personally, I created an array and displayed dropdowns in my page for them to select from, but just as easily, you could create custom links for them to select from as well.  Use your imagination.

Good luck with this, and if you have any questions, feel free to contact me via my homepage at: Joshua Blackstone.Com or comment below.

Thanks.

Thursday, August 15, 2013

MVC Pass Different Model to Partial View

Did a quick search and couldn't find this information anywhere online, so here goes.

Here's my scenario.

I Create new MVC project. (I'm using v4, but it would apply in earlier as well), and choose Internet Application. AccountModels.cs is created in my models folder.

There are 2 classes I'm concerned about. UserProfile and RegisterModel.

My scenario involves saving reuse and creating a partialview for creating and editing the user information. A fairly common scenario in web development. So I create the partialview, and use the Model Declaration of UserProfile. I include all information inside of this that will be reused among the 2 views. In my situation, the password and confirm password are the fields I'm not re-using, so those won't be included in my partialview.

So my views look like:

_UserInfo (Partial View):

@model UserProfile

    @Html.LabelFor(m => m.UserName)
    @Html.TextBoxFor(m => m.UserName)


RegisterPage:

...
Registration Form
       


               @Html.Partial("_UserInfo", Model)

                    @Html.LabelFor(m => m.Password)
                    @Html.PasswordFor(m => m.Password)
               
    ...

    But wait!  This generates an error msg stating that the model type is not the same.  How do I pass a valid model type in so that my controller can still read the data back?

    At the top of the RegistePage, I add the following:

    @model RegisterModel
    @{
        ViewBag.Title = "Register";
        UserProfile user = new UserProfile();
    }

    and change my RegisterPage to pass in user instead of Model, such as:

    @Html.Partial("_UserInfo", user)

    That's it!  Now I can reuse this in an edit profile page and simply use UserProfile as my model type, and pass it into the partialview like:

    @Html.Partial("_UserInfo", Model)

    and the partialview will render it with no problems.



    Thursday, December 1, 2011

    Using JQuery ProgressBar with Long ASP.NET Process

    OK, so maybe others have figured this out, but if so, they haven't written about it. Wanted to use the JQuery Progressbar to display progress results for a long ASP.NET Process.

    First thing was to download a theme from the ThemeRoller site, http://jqueryui.com/themeroller/, and add the jquery library to my project.

    Next, you must create a class to process the status of a ThreadStart Result in ASP.NET. For details on doing this, you can read the Microsoft Documentation, located at: .

    Next, you will need two pages, one for creating the long process, one for showing the progress of the item.

    The majority of the work can be found in the sample code, found at: http://www.joshuablackstone.com/Examples/LongProcess.zip, but the key for me was how to show the progress in the progress bar. First, create your div, such as:

    <div class="progress" rel="0" runat="server" id="progressBar"></div>, and then the code to post the value to the progress bar is set with this function:

    function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
    $("div.progress").each(function () {
    var element = this;
    $(element).progressbar({
    value: parseInt($(element).attr("rel"))
    });
    });
    }
    }

    The reason for the section (if (args.Get_isPartialLoad)) is because an update panel is triggering a timer every two seconds to get the latest value from the threadstart.

    So then, you run the process, which sends the user to the progress page, where they will see a jquery themed progress bar showing progress for the long process, and redirects to a page of your choice when complete.

    Cool.

    Wednesday, September 22, 2010

    JSON Fetch Random Record

    Searched everywhere for this one. Hopefully it will help someone else out...

    I was looking for a way to filter a JSON dataset by an ID number. Here goes...


    1. Step 1 : Create your JSON Data.


      var item = [
      { "id": "0", "language": "English"},
      { "id": "1", "language": "Spanish"},
      { "id": "2", "language": "French"},
      { "id": "3", "language": "Hungarian"}
      ];

    2. Step 2 : Function to find Unique Value:


      I cant take credit for this one. I found this at : http://stackoverflow.com/questions/604935/how-can-i-filter-json-for-unique-key-name-value-pairs. Here it is...

      function getDistinct(o, attr) {
      var answer = {};
      $.each(o, function(index, record) {
      answer[index[attr]] = answer[index[attr]] || [];
      answer[index[attr]].push(record);
      });
      return answer;
      }

    3. Step 3: Create Random Number

      var randNo = Math.floor(Math.random() * 4); (with 4 being the same number of records contained in the JSON Dataset).

    4. Step 4: Return unique record items


      $(function() {
      $.each(getDistinct(markers, "id"), function(groupName, recordArray) {
      var firstRecord = recordArray[randNo];
      $('
    5. ').html(firstRecord.language).appendTo('#results');
      });
      });




    Finally, the body simply contains an unordered list with an id of results to contain the information.

    Friday, September 17, 2010

    ASP.NET Routing 4.0 Handle Error

    OK, so this took a lot of searching, but this worked. Not sure why it isn't put into the Web.Config file initially, or that there isn't more documentation, as this had me going nuts. Anyways, if you get a 404 error on the ASP.NET 4.0 routing feature when you deploy to IIS7.0, take a look at this. I bet it will get you going...

    http://www.gildnersolutions.com/post/2010/04/21/ASPNET-40-URL-problem-with-IIS7.aspx

    Tuesday, July 13, 2010

    Javascript In or Out of Office

    Wanted to create a standard tool to determine if a business is in or out of the office. Fairly standard stuff, but here it is if anyone can use it.


    Needed to check for 3 things.


    1. Holidays

    2. Weekends

    3. Business Hours (in this case 8 to 5)




    Anyways, here's the script that results in a boolean value to determine whether or not the office is open.


    var d = new Date();
    var day = d.getDay();
    var h = d.getHours();
    var y = d.getYear();

    var holidays = ['1/1/' + y,
    '1/21/' + y,
    '2/18/' + y,
    '5/26/' + y,
    '7/4/' + y,
    '9/1/' + y,
    '10/13/' + y,
    '11/11/' + y,
    '11/27/' + y,
    '12/25/' + y,
    '12/31/' + y];

    function isWeekend() {
    if (day == 0 || day == 6) {
    return true;
    }
    else
    {
    return false;
    }
    }

    function isOffHours() {
    if (h < 8 || h > 17) {
    return true;
    }
    else {
    return false;
    }
    }

    function businessClosed() {
    var today = (d.getMonth() + 1) + '/' + d.getDate() + '/' + y;
    if (isWeekend() == true || (jQuery.inArray(today, holidays)) > 0 || isOffHours() == true) {
    return true;
    }
    else {
    return false;
    }
    }

    $(function () {
    if (businessClosed() == true) {
    alert('Sorry, we are closed!');
    }
    else {
    alert('Open for Business!');
    }
    });


    If you want to download, it can be found HERE.

    Thursday, June 17, 2010

    C# vs VB - The debate continues...

    Just getting my feet wet with C#, after being a VB developer for awhile, realizing that C# is getting all of the jobs. With that being said, have run into a few difficulties in converting over, and I'll list a couple here, to be added to as I go along. Consider this a newbie's version of headaches you may face when switching to C#...




    1. In VB, if you want to locate an element inside of a control, you would use:

      Dim control as CONTROLTYPE = CType(CONTAINER.FindControl("ControlID"), CONTROLTYPE)


      In C#, you would write the same expression as:

      CONTROLTYPE control = (CONTROLTYPE)CONTAINER.FindControl("ControlID");

    2. In VB, if you want to place an IIf statement inside of a Label Control, you're free to do so. Simply use

      <%#IIf(Convert.ToString(EXPRESSION)=Something, True, False)%>

      However, when you attempt to use this in C#, you will get an error, as IIf isn't recognized.

      Here's the fix:

      <%# (Convert.ToString(EXPRESSION) == Something ? True : False)%>.

    3. Of Course, & is not recognized, it is replaced by +.

    4. I know when I was creating a VB Side HTML Message, or if I was creating a very long string, I would use '& vbCrLf _'. However, in C#, this changes a bit. Declare your String, and append it just as you would in JS. Example?


      string A = "";

      A += "This is a string ";
      A += " and the second line of the string...";



    I will modify this as I go, but if you are like me, and have done VB this whole time, I would recommend taking any current sites you have done, and redo them from scratch in C#. Get Hung Up? Use THIS as a last resort, it's a pretty good tool.


    Good Luck!