Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

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...

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!

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