Tuesday, June 25, 2013

MVC helper for jquery datePicker

MVC helper creation is very easy and its only requires static method which should return string. Below code is shown how to create textbox with attached jquery date time popup controller.  

public static MvcHtmlString DatePickerFor (this HtmlHelper htmlHelper, Expression<Func> expression, object htmlAttributes = null)
        {
            var body = (MemberExpression)expression.Body;
            var propertyName = body.Member.Name; // get controller id 
            string textbox = htmlHelper.EditorFor(expression).ToString();
           var script = "'<'script type=\"text/javascript\'>'"
$('#" + propertyName + "').datepicker();

            script += "'<'/script'>'"

            return MvcHtmlString.Create(textbox + "\n" + script);
        }

In the view you can access this helper as below

@Html.DatePickerFor (model => model.dateField)

 Above code is shown the basic steps of required html helper. Assume that want to add more html attributes, date format and other specific filter criteria inside the method and can be pass parameter from view page. This helper is useful you need to add business logic  and validation required before binding data to view. 

public static MvcHtmlString DatePickerFor(this HtmlHelper htmlHelper, Expression<Func> expression, object htmlAttributes = null)
        {
            var body = (MemberExpression)expression.Body;
            var propertyName = body.Member.Name; // get controller id 
            var attr = new RouteValueDictionary(htmlAttributes); // html attributes 

            string propertyDateFormat = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).DisplayFormatString;

// logic and validation 
            string dateFormat = "";

            if (propertyDateFormat == "{0:dd/MM/yyyy}")
                dateFormat = "dd/mm/yy";
            else               
                dateFormat = "dd/mm/yy";

            string textbox = htmlHelper.EditorFor(expression).ToString(); // render html text box 

                        var script = "'<'script type=\"text/javascript\"'>'$('#" + propertyName + "').datepicker({ dateFormat: '" + dateFormat + "' }); $('#" + propertyName + "').removeClass('text-box');";
            if (attr["style"] != null)
                script += "$('#" + propertyName + "').attr('style','" + attr["style"] + "');";
            if (attr["class"] != null)
                script += "$('#" + propertyName + "').addClass('" + attr["class"] + "');";
            script += "'<'/script'>'";


            return MvcHtmlString.Create(textbox + "\n" + script);        }

without above helper we can used jquery date picker but if need to add some server side validation and server side controlled then this way is more easy.  


1 comment:

  1. this link will be helpful , it has more details about html helpers
    http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs

    ReplyDelete