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!

    Wednesday, June 9, 2010

    Thank You Ryan Grove - Finally a Script Loader that works painlessly!

    Finally was able to make my homepage not CRAWL due to a lazy script loader that I found. Prior to this, either security was too tight from GoDaddy or it was just made for Image Files. Anyways, check this out...


    http://wonko.com/post/painless_javascript_lazy_loading_with_lazyload