Thursday, January 19, 2012

Replacement for LabelFor in ASP.NET MVC 3

As I've been deep-diving further into ASP.Net MVC 3, I ran into an issue where I needed to arbitrarily show an indicator against a label that would tell me which fields are required.  We were initially doing this by hand, but have been using a ton of inheritance to set [Required] attributes on fields.  In order to overcome this pain, we decided to create a helper method that we now use instead of @Html.LabelFor()... it looks like this (Exactly from *.cs file):

using System.Linq;
using System.Linq.Expressions;

namespace System.Web.Mvc
{
    public static class HtmlHelpers
    {
        public static MvcHtmlString LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, 
            Expression<Func<TModel, TValue>> expression,
            string id="", bool generatedId=false)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var htmlFieldName = ExpressionHelper.GetExpressionText(expression);

            if (metadata.IsRequired)
            {
                var labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
                if (string.IsNullOrWhiteSpace(labelText))
                {
                    return MvcHtmlString.Empty;
                }

                var tag = new TagBuilder("label");
                var spanTag = new TagBuilder("span");
                spanTag.AddCssClass("required");
                spanTag.SetInnerText("*");

                if (!string.IsNullOrWhiteSpace(id))
                {
                    tag.Attributes.Add("id", id);
                }
                else if (generatedId)
                {
                    tag.Attributes.Add("id", htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName) + "_Label");
                }


                tag.Attributes.Add("for", htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
                tag.SetInnerText(labelText);

                return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal) + "&nbsp;" + spanTag.ToString(TagRenderMode.Normal));
            }
            else
            {
                return System.Web.Mvc.Html.LabelExtensions.LabelFor(htmlHelper, expression);
            }
        }
    }
}


Hope that this helps someone...

Wednesday, December 7, 2011

Client-Side Model-Aware Validation in MVC3

Just a note so mostly, I remember.

I've been working with Nick Riggs' Foolproof validation in MVC3, trying to get more complex scenarios in place, and needed to write the client validation.  He has a great post for MVC2 at
http://www.nickriggs.com/posts/client-side-model-aware-validation/, but it doesn't cover MVC3.

After some research, etc., here is what I came up with for something very simplistic, where it's just making sure a value is set, etc...

$(function () {

    jQuery.validator.addMethod('listrequirediftrue', function (value, element, param) {
        if (param) {
            return $('#' + $(element).attr('id') + ' option:selected').length > 0;
        }

        return true;
    }, '');
    jQuery.validator.unobtrusive.adapters.add('listrequirediftrue', {}, function (options) {

        if (options.message) {
            options.rules['listrequirediftrue'] = true;
            options.messages['listrequirediftrue'] = options.message;
        }

    });
} (jQuery));

I just need to now figure out for more complex scenarios, like when you have a RequiredIf, but dependent on when another dropdown has a certain value.  Nick has the RequiredIfAttribute, but when you're validating based on an entire model, where the property to be validated is not at the same level as the property whose value is the "RequiredIf" property, you have to use the ModelAware style of validation... will update when I have an answer.

Thursday, November 3, 2011

More quirks with ASP.NET MVC 3

So, another great quirk with ASP.NET MVC 3.  When you implement a controller with two methods, one being for the initial load of the page, and the other being for the subsequent form post to process the data... if your intention is to re-render the page to do another 'Add Item' scenario, you must issue a ModelState.Clear(); command before you render the new view... otherwise, it seems to keep the values from the posted data.

Monday, June 27, 2011

ASP.NET MVC3 has a few quirks

http://aspnet.codeplex.com/workitem/7629

Ack!  Seems like this shouldn't have happened. 

To correct, you have to do the following:

Give your select list the "Required" attribute.
Once the page loads, in jQuery, assign the data-val attribute and the data-val-message attributes.

Microsoft, this is not good!

Tuesday, June 7, 2011

Team Foundation Server 2010 isn't friendly for certain items...

It seems as if this is a normally recurring issue with build automation and Team Foundation Server 2010 specifically.  Utilizing Team Foundation Server's build automation, it takes the *.sln and *.csproj files and utilizes that to create the output binaries as expected.  What is unfortunate is that the .Net SDK doesn't have everything that you need to handle build automation on a build server, so you're forced to do one of 2 things:
  1. Deploy VS.Net 2010 on your build server(s)
  2. Copy the files from c:\{Program Files x86}\MSBuild\Microsoft\VisualStudio\... to your build machine.
Honestly, both solutions break the fundamental rules of using a build automation server, IMHO.  Completely disappointed Microsoft! I think that I'll be writing ScottGU or someone else to see if they have a better solution to handle this case, as it's simply a poor "workaround" solution.

Thursday, June 2, 2011

Textarea Autoexpand Javascript code.

As part of a project for a consulting job I'm on, the need we had was to give a forever expanding text area on the html form.  This is the javascript I wrote to do just that.  I'm sharing it because mainly, I think it's cool!

I should have documented how this works. What you'll do in the Html is to define a text area (could be an asp TextBox with its mode set to Multiple, or a generic TextArea tag... either way, they render out the same.) and you'll add an attribute called expandable and set its value equal to True.  From there, reference jQuery in your header, and this code should work for you as-is.

Have at it, and comment if you see where I could improve in some way.

          function formatPage() {
            $(document).find('*[expandable]').keyup(function () {
                var height = 0;
                var existingHeight = this.style.height;
                var lines = this.value.split('\r');
                this.style.height = '';
                for (x = 0; x < lines.length; x++) {
                    var lengthOverflow = lines[x].length % this.cols;

                    height = height + (14 * (((lines[x].length - lengthOverflow) / this.cols)));
                    if (lengthOverflow > 0) {
                        height = height + 14;
                    }
                }

                if (height == 0) {
                    height = 14;
                }

                if (existingHeight != height) {
                    this.style.height = height + 'px';
                }
            });

            $(document).find('*[expandable]').keyup();
        }

        $(document).ready(function () {
            formatPage();
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
        });


        function endRequestHandler(sender, args) {
            formatPage();
        }

Saturday, December 4, 2010

A few changes on the horizon

It's been a while since I've last written a blog post.  Much to my amazement, there has been a few changes in the past n months that are scary and exciting at the same time.

I decided it is time to leave behind an old project and start to look ahead.  I'm starting by taking a 6 month contract position with someone, and be forced back into 8 hour shifts, so I can get my full day stamina back.  The past three years has been rather hectic with family woes and pulling many days on the road, not to mention, many late night coding/testing sessions to support a client base that I never had access to in the beginning.

A business contact discussed a new business venture with me that if all works well, we should be starting in the next six months, right after I finish the contract position with whichever company I choose to work with.  This venture is going to be a culmination of everything that I've done in the past 5 years, utilizing the recent education of learning how to properly deploy an application, how to use the latest and greatest in technology, and to even now be able to use some technology that is still being developed from the folks at Microsoft.  I can't wait to get started... it should be a wild ride.

As we go, the hope is to keep posting occasionally on the progress of the project, and maybe a tidbit or two of what the project is.  Again, I can't wait to get the project going, and to-market... it's going to be a wild ride!