예제 #1
0
        /// <summary>
        /// Creates a Bootstrap icon
        /// </summary>
        /// <param name="icon">Icon to be created</param>
        /// <param name="htmlAttributes">[Optional] Any extra HTML attributes</param>
        /// <returns>A Bootstrap icon</returns>
        public static IHtmlComponent CreateIcon(EBootstrapIcon icon, object htmlAttributes = null)
        {
            NameValueCollection htmlAttribs = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes);

            List <string> cssClasses = new List <string>();

            if (htmlAttribs.ContainsKey("class"))
            {
                cssClasses.AddRange(htmlAttribs["class"].Split(' '));
                htmlAttribs.Remove("class");
            }

            switch (WebExtrasSettings.BootstrapVersion)
            {
            case EBootstrapVersion.V2:
                cssClasses.Add("icon-" + icon.ToString().ToLowerInvariant().Replace("_", "-"));
                break;

            case EBootstrapVersion.V3:
                cssClasses.Add("glyphicon glyphicon-" + icon.ToString().ToLowerInvariant().Replace("_", "-"));
                break;

            default:
                throw new BootstrapVersionException();
            }

            HtmlComponent i = new HtmlComponent(EHtmlTag.I);

            i.CssClasses.AddRange(cssClasses);
            return(i);
        }
예제 #2
0
        /// <summary>
        ///   Create a label with the required field asterix
        /// </summary>
        /// <typeparam name="TModel">Type to be scanned</typeparam>
        /// <typeparam name="TValue">Property to be scanned</typeparam>
        /// <param name="html">Htmlhelper extension</param>
        /// <param name="expression">The property lamba expression</param>
        /// <param name="labelText">Label text to be shown</param>
        /// <param name="htmlAttributes">[Optional] Extra html attributes</param>
        /// <returns>A label with the required field asterix</returns>
        public static IExtendedHtmlString RequiredFieldLabelFor <TModel, TValue>(this HtmlHelpers <TModel> html,
                                                                                 Expression <Func <TModel, TValue> > expression, string labelText, object htmlAttributes = null)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            MemberExpression exp = expression.Body as MemberExpression;

            if (exp == null)
            {
                throw new ArgumentException("Unable to parse property lambda expression", "expression");
            }

            HtmlComponent label = new HtmlComponent(EHtmlTag.Label, htmlAttributes);

            label.Attributes["id"]   = WebExtrasUtil.GetFieldIdFromExpression(exp);
            label.Attributes["name"] = WebExtrasUtil.GetFieldNameFromExpression(exp);
            label.InnerHtml          = labelText;

            if (exp.Member.GetCustomAttributes(typeof(RequiredAttribute), true).Any())
            {
                HtmlComponent span = new HtmlComponent(EHtmlTag.Span);
                span.CssClasses.Add("required");
                span.InnerHtml = " *";

                label.AppendTags.Add(span);
            }

            return(new ExtendedHtmlString(label));
        }
        /// <summary>
        ///   Create bootstrap 3 tags
        /// </summary>
        /// <param name="htmlAttributes">Extra HTML attributes</param>
        private void CreateBootstrap3Tags(object htmlAttributes)
        {
            var defaultAttribs = new Dictionary <string, string>
            {
                { "type", "text" },
                { "id", WebExtrasUtil.GetFieldIdFromExpression(m_propertyExpression) },
                { "name", WebExtrasUtil.GetFieldNameFromExpression(m_propertyExpression) }
            };

            DataTypeAttribute[] customAttribs =
                (DataTypeAttribute[])m_propertyExpression.Member.GetCustomAttributes(typeof(DataTypeAttribute), false);
            if (customAttribs.Length > 0)
            {
                switch (customAttribs[0].DataType)
                {
                case DataType.EmailAddress:
                    defaultAttribs["type"] = "email";
                    break;

                case DataType.Password:
                    defaultAttribs["type"] = "password";
                    break;

                case DataType.MultilineText:
                    defaultAttribs["type"] = "textarea";
                    break;
                }
            }

            Dictionary <string, string> attribs = WebExtrasUtil
                                                  .AnonymousObjectToHtmlAttributes(htmlAttributes)
                                                  .ToDictionary()
                                                  .Merge(defaultAttribs)
                                                  .ToDictionary(k => k.Key, v => v.Value);

            HtmlComponent input;

            if (m_selectListItems != null)
            {
                input = new HtmlSelect(m_selectListItems, attribs);
            }
            else if (m_textAreaDimensions != null || attribs.ContainsValue("textarea"))
            {
                attribs.Remove("type");

                input = new HtmlComponent(EHtmlTag.TextArea, attribs);
            }
            else
            {
                input = new HtmlComponent(EHtmlTag.Input, attribs);
            }

            input.CssClasses.Add("form-control");

            Input      = input;
            InputGroup = new HtmlComponent(EHtmlTag.Div);
            InputGroup.CssClasses.Add("input-group");
            InputGroup.AppendTags.Add(input);
        }
예제 #4
0
        /// <summary>
        ///   Creates a Bootstrap date time picker control
        /// </summary>
        /// <typeparam name="TModel">Type to be scanned</typeparam>
        /// <typeparam name="TValue">Property to be scanned</typeparam>
        /// <param name="html">HtmlHelper extension</param>
        /// <param name="expression">The property lamba expression</param>
        /// <param name="options">Date time picker options</param>
        /// <param name="htmlAttributes">Extra HTML attributes to be applied to the text box</param>
        /// <returns>A Bootstrap date time picker control</returns>
        public static IExtendedHtmlString DateTimeTextBoxFor <TModel, TValue>(this HtmlHelpers <TModel> html,
                                                                              Expression <Func <TModel, TValue> > expression,
                                                                              PickerOptions options, object htmlAttributes)
        {
            MemberExpression mex = expression.Body as MemberExpression;

            string id   = WebExtrasUtil.GetFieldIdFromExpression(mex);
            string name = WebExtrasUtil.GetFieldNameFromExpression(mex);

            IHtmlComponent control = new DateTimePickerHtmlComponent(name, id, options, htmlAttributes);

            return(new ExtendedHtmlString(control));
        }
예제 #5
0
        /// <summary>
        /// Creates an icon
        /// </summary>
        /// <param name="icon">Icon to be created</param>
        /// <param name="htmlAttributes">[Optional] Any extras HTML attributes</param>
        /// <returns>A Gumby icon</returns>
        public static IHtmlComponent CreateIcon(EGumbyIcon icon, object htmlAttributes = null)
        {
            NameValueCollection attrsDictionary = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes);

            HtmlComponent i = new HtmlComponent(EHtmlTag.I);

            i.CssClasses.Add("icon-" + icon.ToString().ToLowerInvariant().Replace('_', '-'));

            foreach (string key in attrsDictionary.Keys)
            {
                i.Attributes[key] = attrsDictionary[key];
            }

            return(i);
        }
예제 #6
0
        /// <summary>
        ///   Ignore validation errors for given properties
        /// </summary>
        /// <typeparam name="TModel">Model type</typeparam>
        /// <param name="modelstate">Current model state dictionary</param>
        /// <param name="expression">Property selectors</param>
        public static void IgnoreErrorsFor <TModel>(this ModelStateDictionary modelstate,
                                                    params Expression <Func <TModel, object> >[] expression)
        {
            if (expression == null)
            {
                return;
            }

            if (expression.Length == 0)
            {
                return;
            }

            Array.ForEach(expression,
                          f => modelstate.Remove(WebExtrasUtil.GetFieldNameFromExpression(f.Body as MemberExpression)));
        }
예제 #7
0
        /// <summary>
        ///   Get property errors
        /// </summary>
        /// <typeparam name="TModel">Model type</typeparam>
        /// <param name="modelstate">Current model state dictionary</param>
        /// <param name="expression">Property selector</param>
        /// <returns>Property errors if found, else null</returns>
        /// <exception cref="ArgumentNullException">If expression is null</exception>
        public static ModelState GetPropertyErrorsFor <TModel>(this ModelStateDictionary modelstate,
                                                               Expression <Func <TModel> > expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            string key = WebExtrasUtil.GetFieldNameFromExpression(expression.Body as MemberExpression);

            if (modelstate.ContainsKey(key))
            {
                return(modelstate[key]);
            }

            return(null);
        }
예제 #8
0
        /// <summary>
        /// Creates a Bootstrap Font-Awesome icon
        /// </summary>
        /// <param name="icon">Icon to be rendered</param>
        /// <param name="size">Icon size</param>
        /// <param name="htmlAttributes">Extra HTML attributes</param>
        /// <returns>A Bootstrap icon</returns>
        /// <exception cref="FontAwesomeVersionException">Thrown when a valid FontAwesome
        /// icon library version is not selected</exception>
        public static IHtmlComponent CreateIcon(EFontAwesomeIcon icon, EFontAwesomeIconSize size = EFontAwesomeIconSize.Normal, object htmlAttributes = null)
        {
            NameValueCollection attrsDictionary = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes);

            List <string> cssClasses = new List <string>();

            if (attrsDictionary.ContainsKey("class"))
            {
                cssClasses.AddRange(attrsDictionary["class"].Split(' '));
                attrsDictionary.Remove("class");
            }

            string prefix;

            switch (WebExtrasSettings.FontAwesomeVersion)
            {
            case EFontAwesomeVersion.V3:
                prefix = "icon-";
                break;

            case EFontAwesomeVersion.V4:
                prefix = "fa fa-";
                break;

            default:
                throw new FontAwesomeVersionException();
            }

            cssClasses.Add(prefix + icon.ToString().ToLowerInvariant().Replace("_", "-"));

            if (size != EFontAwesomeIconSize.Normal)
            {
                cssClasses.Add(prefix + size.GetStringValue());
            }

            HtmlComponent i = new HtmlComponent(EHtmlTag.I);

            i.CssClasses.AddRange(cssClasses);

            foreach (string key in attrsDictionary.Keys)
            {
                i.Attributes[key] = attrsDictionary[key];
            }

            return(i);
        }
예제 #9
0
        /// <summary>
        ///   Constructor to specify extra HTML attributes as an anonymous type
        /// </summary>
        /// <param name="tag">An HTML tag to initialise this element with</param>
        /// <param name="htmlAttributes">Extra HTML attributes</param>
        public HtmlComponent(EHtmlTag tag, object htmlAttributes = null)
        {
            Tag        = tag;
            Attributes = new Dictionary <string, string>();
            CssClasses = new CssClassList();

            AppendTags  = new HtmlComponentList();
            PrependTags = new HtmlComponentList();

            if (htmlAttributes == null)
            {
                return;
            }

            bool isDict = (htmlAttributes as IDictionary <string, string>) != null;

            if (isDict)
            {
                Attributes = (IDictionary <string, string>)htmlAttributes;
                if (!Attributes.ContainsKey("class"))
                {
                    return;
                }

                CssClasses.Add(Attributes["class"]);
                Attributes.Remove("class");

                return;
            }

            NameValueCollection attribs = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes);

            foreach (string key in attribs.Keys)
            {
                if (key.Equals("class", StringComparison.OrdinalIgnoreCase))
                {
                    CssClasses.Clear();
                    CssClasses.Add(attribs[key]);
                    continue;
                }

                Attributes[key] = attribs[key];
            }
        }
예제 #10
0
        /// <summary>
        /// Creates a jQuery UI icon
        /// </summary>
        /// <param name="icon">Icon to be created</param>
        /// <param name="htmlAttributes">[Optional] Any extra HTML attributes</param>
        /// <returns>A jQuery UI icon</returns>
        public static IHtmlComponent CreateIcon(EJQueryUIIcon icon, object htmlAttributes = null)
        {
            NameValueCollection rvd = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes);

            List <string> cssClasses = new List <string>();

            if (rvd.ContainsKey("class"))
            {
                cssClasses.AddRange(rvd["class"].Split(' '));
                rvd.Remove("class");
            }

            cssClasses.Add("ui-icon");
            cssClasses.Add("ui-icon-" + icon.ToString().ToLowerInvariant().Replace("_", "-"));

            HtmlComponent i = new HtmlComponent(EHtmlTag.I);

            i.CssClasses.AddRange(cssClasses);

            return(i);
        }
        /// <summary>
        ///   Gets the validation state of a property
        /// </summary>
        /// <typeparam name="TModel">Type to be scanned</typeparam>
        /// <typeparam name="TValue">Property to be scanned</typeparam>
        /// <param name="html">Htmlhelper extension</param>
        /// <param name="expression">The property lambda expression</param>
        /// <returns>True if state is valid, else False</returns>
        public static bool IsValidFor <TModel, TValue>(this HtmlHelper <TModel> html,
                                                       Expression <Func <TModel, TValue> > expression)
        {
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            MemberExpression exp = expression.Body as MemberExpression;

            string mname = WebExtrasUtil.GetFieldNameFromExpression(exp);

            bool result = true;

            if (html.ViewData.ModelState.ContainsKey(mname))
            {
                result = !(html.ViewData.ModelState[mname].Errors.Count > 0);
            }

            return(result);
        }
예제 #12
0
        /// <summary>
        ///   Add an icon
        /// </summary>
        /// <typeparam name="T">Generic type to be used. This type must implement IExtendedHtmlString</typeparam>
        /// <param name="html">Current html element</param>
        /// <param name="cssClasses">Css classes to be added</param>
        /// <param name="htmlAttributes">[Optional] Extra html attributes</param>
        /// <returns>HTML element with icon added</returns>
        private static T AddIcon <T>(T html, IEnumerable <string> cssClasses, object htmlAttributes = null)
            where T : IExtendedHtmlString
        {
            NameValueCollection rvd = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes);

            List <string> finalClasses = new List <string>(cssClasses);

            if (rvd.ContainsKey("class"))
            {
                finalClasses.AddRange(rvd["class"].Split(' '));
                rvd.Remove("class");
            }

            HtmlComponent i = new HtmlComponent(EHtmlTag.I);

            i.CssClasses.AddRange(finalClasses);

            foreach (string key in rvd.Keys)
            {
                i.Attributes[key] = rvd[key];
            }

            // TODO: remove unnecessary conversion
            html.Component.PrependTags.Add(i);

            if (html.Component.Attributes.ContainsKey("style"))
            {
                html.Component.Attributes["style"] += ";text-decoration:none";
            }
            else
            {
                html.Component.Attributes["style"] = "text-decoration:none";
            }

            return(html);
        }
예제 #13
0
        /// <summary>
        ///   Generate ID for a model property
        /// </summary>
        /// <typeparam name="TModel">Type to be scanned</typeparam>
        /// <typeparam name="TValue">Property to be scanned</typeparam>
        /// <param name="html">Current HTML helper object</param>
        /// <param name="expression">Member expression</param>
        /// <returns>Generated HTML ID</returns>
        public static string GenerateIdFor <TModel, TValue>(this HtmlHelper html, Expression <Func <TModel, TValue> > expression)
        {
            string propertyName = WebExtrasUtil.GetFieldNameFromExpression(expression.Body as MemberExpression);

            return(html.GenerateId(propertyName));
        }
예제 #14
0
        /// <summary>
        ///   Creates a Bootstrap date time picker control
        /// </summary>
        /// <typeparam name="TModel">Type to be scanned</typeparam>
        /// <typeparam name="TValue">Property to be scanned</typeparam>
        /// <param name="html">HtmlHelper extension</param>
        /// <param name="expression">The property lamba expression</param>
        /// <param name="options">Date time picker options</param>
        /// <param name="htmlAttributes">Extra HTML attributes to be applied to the text box</param>
        /// <returns>A Bootstrap date time picker control</returns>
        public static IExtendedHtmlStringLegacy DateTimeTextBoxFor <TModel, TValue>(this HtmlHelper <TModel> html,
                                                                                    Expression <Func <TModel, TValue> > expression, PickerOptions options,
                                                                                    object htmlAttributes = (IDictionary <string, object>) null)
        {
            MemberExpression exp = expression.Body as MemberExpression;

            PickerOptions pickerOptions =
                options.GetHashCode() == BootstrapSettings.DateTimePickerOptions.GetHashCode()
          ? options.DeepClone()
          : options;

            pickerOptions = pickerOptions.TryFontAwesomeIcons();

            var model = ((DateTime?)ModelMetadata.FromLambdaExpression(expression, html.ViewData).Model);

            if (model.HasValue && model.Value > DateTime.MinValue)
            {
                pickerOptions.defaultDate = model;
            }

            string fieldId   = WebExtrasUtil.GetFieldIdFromExpression(exp);
            string fieldName = WebExtrasUtil.GetFieldNameFromExpression(exp);

            // create the text box
            HtmlComponent input   = new HtmlComponent(EHtmlTag.Input);
            var           attribs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)
                                    .ToDictionary(k => k.Key, v => v.Value.ToString());

            input.Attributes.Add(attribs);
            input.Attributes["type"] = "text";
            input.Attributes["name"] = fieldName;

            if (input.Attributes.ContainsKey("class"))
            {
                input.Attributes["class"] += " form-control";
            }
            else
            {
                input.Attributes["class"] = "form-control";
            }

            // create icon
            HtmlComponent icon = new HtmlComponent(EHtmlTag.I);

            if (WebExtrasSettings.FontAwesomeVersion == EFontAwesomeVersion.V4)
            {
                icon.CssClasses.Add("fa fa-calendar");
            }
            else if (WebExtrasSettings.FontAwesomeVersion == EFontAwesomeVersion.V3)
            {
                icon.CssClasses.Add("icon-calendar");
            }
            else
            {
                icon.CssClasses.Add("glyphicon glyphicon-calendar");
            }

            // create addon
            HtmlComponent addOn = new HtmlComponent(EHtmlTag.Span);

            addOn.CssClasses.Add("input-group-addon");
            addOn.AppendTags.Add(icon);

            // create JSON dictionary of the picker options
            string op = pickerOptions.ToJson(new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            HtmlComponent script = new HtmlComponent(EHtmlTag.Script);

            script.Attributes["type"] = "text/javascript";
            script.InnerHtml          = "$(function(){ $('#" + fieldId + "').datetimepicker(" + op + "); });";

            // create the final component
            IHtmlComponent control;

            if (pickerOptions.useAddonField.Equals(false))
            {
                NullWrapperComponent wrapper = new NullWrapperComponent();

                input.Attributes["id"] = fieldId;
                wrapper.Components.Add(input);

                wrapper.Components.Add(script);

                control = wrapper;
            }
            else
            {
                control = new HtmlComponent(EHtmlTag.Div);
                control.Attributes["id"]    = fieldId;
                control.Attributes["class"] = "input-group date";
                control.AppendTags.Add(input);
                control.AppendTags.Add(addOn);
                control.AppendTags.Add(script);
            }

            return(new HtmlElement(control));
        }
예제 #15
0
        /// <summary>
        ///   Creates a Bootstrap date time picker control
        /// </summary>
        /// <typeparam name="TModel">Type to be scanned</typeparam>
        /// <typeparam name="TValue">Property to be scanned</typeparam>
        /// <param name="html">HtmlHelper extension</param>
        /// <param name="expression">The property lamba expression</param>
        /// <param name="options">Date time picker options</param>
        /// <param name="htmlAttributes">Extra HTML attributes to be applied to the text box</param>
        /// <returns>A Bootstrap date time picker control</returns>
        public static MvcHtmlString DateTimeTextBoxFor <TModel, TValue>(this HtmlHelper <TModel> html,
                                                                        Expression <Func <TModel, TValue> > expression, PickerOptions options,
                                                                        object htmlAttributes = (IDictionary <string, object>) null)
        {
            MemberExpression exp = expression.Body as MemberExpression;

            PickerOptions pickerOptions =
                options.GetHashCode() == BootstrapSettings.DateTimePickerOptions.GetHashCode()
          ? options.DeepClone()
          : options;

            pickerOptions = pickerOptions.UpdateOptionsBasedOnView();

            string fieldId        = WebExtrasUtil.GetFieldIdFromExpression(exp);
            string fieldName      = WebExtrasUtil.GetFieldNameFromExpression(exp);
            string datetimeformat = ConvertToCsDateFormat(pickerOptions.format);

            // create the text box
            TagBuilder input = new TagBuilder("input");

            input.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
            input.Attributes["type"]  = "text";
            input.Attributes["value"] =
                ((DateTime)ModelMetadata.FromLambdaExpression(expression, html.ViewData).Model).ToString(datetimeformat);
            input.Attributes["name"] = fieldName;

            if (input.Attributes.ContainsKey("class"))
            {
                input.Attributes["class"] += " form-control";
            }
            else
            {
                input.Attributes["class"] = "form-control";
            }

            // create addon
            TagBuilder addOn = new TagBuilder("span");

            addOn.AddCssClass("add-on");

            TagBuilder icons = new TagBuilder("i");

            icons.AddCssClass("icon-calendar");

            TagBuilder control = new TagBuilder("div");

            control.Attributes["id"]    = fieldId;
            control.Attributes["class"] = "input-append date form_datetime";

            addOn.InnerHtml   = icons.ToString(TagRenderMode.Normal);
            control.InnerHtml = input.ToString(TagRenderMode.SelfClosing) + addOn.ToString(TagRenderMode.Normal);

            // create JSON dictionary of the picker options
            string op = pickerOptions.ToJson();

            TagBuilder script = new TagBuilder("script");

            script.Attributes["type"] = "text/javascript";
            script.InnerHtml          = "$(function(){ $('#" + fieldId + "').datetimepicker(" + op + "); });";

            return(MvcHtmlString.Create(control.ToString(TagRenderMode.Normal) + script.ToString(TagRenderMode.Normal)));
        }
        /// <summary>
        ///   Constructor
        /// </summary>
        /// <param name="name">HTML field name</param>
        /// <param name="id">HTML field id</param>
        /// <param name="options">Date time picker options</param>
        /// <param name="htmlAttributes">Extra HTML attributes</param>
        public DateTimePickerHtmlComponent(string name, string id, PickerOptions options, object htmlAttributes)
            : base(EHtmlTag.Div)
        {
            PickerOptions pickerOptions =
                (options ?? BootstrapSettings.DateTimePickerOptions).TryFontAwesomeIcons();

            string fieldId   = id;
            string fieldName = name;

            // create the text box
            HtmlComponent input   = new HtmlComponent(EHtmlTag.Input);
            var           attribs = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes).ToDictionary();

            input.Attributes.Add(attribs);
            input.Attributes["type"] = "text";
            input.Attributes["name"] = fieldName;

            if (input.Attributes.ContainsKey("class"))
            {
                input.Attributes["class"] += " form-control";
            }
            else
            {
                input.Attributes["class"] = "form-control";
            }

            // create icon
            HtmlComponent icons = new HtmlComponent(EHtmlTag.I);

            if (WebExtrasSettings.FontAwesomeVersion == EFontAwesomeVersion.V4)
            {
                icons.CssClasses.Add("fa fa-calendar");
            }
            else if (WebExtrasSettings.FontAwesomeVersion == EFontAwesomeVersion.V3)
            {
                icons.CssClasses.Add("icon-calendar");
            }
            else
            {
                icons.CssClasses.Add("glyphicon glyphicon-calendar");
            }

            // create addon
            HtmlComponent addOn = new HtmlComponent(EHtmlTag.Span);

            addOn.CssClasses.Add("input-group-addon");
            addOn.AppendTags.Add(icons);

            // create JSON dictionary of the picker options
            string op = pickerOptions.ToJson(new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            HtmlComponent script = new HtmlComponent(EHtmlTag.Script);

            script.Attributes["type"] = "text/javascript";
            script.InnerHtml          = "$(function(){ $('#" + fieldId + "').datetimepicker(" + op + "); });";

            // setup up datetime picker
            Attributes["id"]    = fieldId;
            Attributes["class"] = "input-group date";
            AppendTags.Add(input);
            AppendTags.Add(addOn);
            AppendTags.Add(script);
        }