0

I have created htmlhelper,

I have been wondering, if there is some neater way of doing this. Please feel free to say what i am doing wrong, your suggestions are welcome.

    /// <summary>
    /// Custom jQuery Picker for object
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    /// <typeparam name="TProperty"></typeparam>
    /// <param name="htmlHelper"></param>
    /// <param name="expression"></param>
    /// <returns></returns>
    public static string DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
    {
      //gets name of object
      string fullHtmlFieldName = htmlHelper
                             .ViewContext
                             .ViewData
                             .TemplateInfo
                             .GetFullHtmlFieldName(
                                 ExpressionHelper.GetExpressionText(expression)
                             );
      //returns metadata for object
      var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
      DateTime date;
      DateTime.TryParse(metaData.Model.ToString(), out date); // will be of type TProperty
      StringBuilder html = new StringBuilder();
      string attributes = "";
      string objectId = fullHtmlFieldName;

      if (htmlAttributes.Count != 0)
      {
        foreach (KeyValuePair<string, object> element in htmlAttributes)
        {
          attributes += element.Key.ToLower() +"=\""+ element.Value+"\" ";
          if (element.Key.ToLower() == "id") objectId = element.Value.ToString();
        }           
      }

      html.Append("<input type=\"text\" name=\"" + fullHtmlFieldName + "\" " + attributes + " ");
      if (date != null) html.Append(" value=\"" + date.ToShortDateString() + "\"");
      html.Append("/>");
      html.Append("<script type=\"text/javascript\">$(document).ready(function() { $('#" + objectId + "').datepicker({rangeSelect: true,changeMonth: true,changeYear: true, firstDay: 1, duration: 'fast'}); });</script>");
      return html.ToString();

Also i want to ask, is there any possibility to assign parts of code be automatically parsed, allocated to diferent ContentPlaceHolders

eg: script part of the code will be rendered inside following ContentPlaceHolder:

<asp:ContentPlaceHolder ID="JavaScript" runat="server" />
cpoDesign
  • 8,953
  • 13
  • 62
  • 106

1 Answers1

0

Instead of implementing a custom HtmlHelper extension, you can use Templating and Html.EditorFor(). I've been using them for a while with no problems. The following links can help you:

CGK
  • 2,662
  • 21
  • 24