Example #1
0
        /// <summary>Generate a control for a range preference.</summary>
        private static string RangePreferenceControl(HtmlHelper helper, MetaAttribute ma, Preference preference)
        {
            string lowerBoundControl;
            string upperBoundControl;
            string currentLowerBound = null;
            string currentUpperBound = null;

            if (preference != null)
            {
                currentLowerBound = (preference.Range.LowerBound != null) ? preference.Range.LowerBound.Formatted : String.Empty;
                currentUpperBound = (preference.Range.UpperBound != null) ? preference.Range.UpperBound.Formatted : String.Empty;
            }

            if (ma.HasChoices)
            {
                SelectList lowerBoundListData = (preference != null)
                    ? new SelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text", currentLowerBound)
                    : new SelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text");
                SelectList upperBoundListData = (preference != null)
                    ? new SelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text", currentUpperBound)
                    : new SelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text");

                lowerBoundControl = helper.DropDownList(ma.PreferenceLowerBoundHtmlControlName, lowerBoundListData, OPTION_LABEL);
                upperBoundControl = helper.DropDownList(ma.PreferenceUpperBoundHtmlControlName, upperBoundListData, OPTION_LABEL);
            }
            else
            {
                lowerBoundControl = helper.TextBox(ma.PreferenceLowerBoundHtmlControlName, currentLowerBound, new {length=10});
                upperBoundControl = helper.TextBox(ma.PreferenceUpperBoundHtmlControlName, currentUpperBound, new {length=10});
            }

            return String.Format(
                "From {2}{0} to {2}{1}", lowerBoundControl, upperBoundControl, (ma.DataTypeEnum == MetaAttribute.MetaAttributeDataType.CURRENCY) ? "$" : String.Empty);
        }
        private static String RenderElementByType(HtmlHelper html, FormElement model, String elementName, String elementValue)
        {
            var builder = new StringBuilder();
            switch (model.Type)
            {
                case FormElementType.TextField:
                    {
                        builder.Append(html.Encode(model.Title));
                        break;
                    }
                case FormElementType.TextBox:
                    {
                        builder.Append(html.Label(elementName, model.Title));
                        builder.Append("<br/>");
                        builder.Append(html.TextBox(elementName, elementValue));
                        break;
                    }
                case FormElementType.TextArea:
                    {
                        builder.Append(html.Label(elementName, model.Title));
                        builder.Append("<br/>");
                        builder.Append(html.TextArea(elementName, elementValue));
                        break;
                    }
                case FormElementType.CheckBox:
                    {
                        builder.Append(html.SimpleCheckBox(elementName, FormCollectionExtensions.BooleanValue(elementValue)));
                        builder.Append(html.Label(elementName, model.Title));
                        break;
                    }
                case FormElementType.DropDownList:
                    {
                        builder.Append(html.Label(elementName, model.Title));
                        builder.Append("<br/>");
                        builder.Append(html.DropDownList(elementName, ParseElementValuesForDropDown(model.ElementValues, elementValue)));
                        break;
                    }
                case FormElementType.RadioButtons:
                    {
                        builder.Append(html.Label(elementName, model.Title));
                        builder.Append("<br/>");
                        builder.Append(html.RadioList(elementName, ParseElementValuesForRadioButtons(model.ElementValues, elementName), elementValue));
                        break;
                    }
                case FormElementType.Captcha:
                    {
                        builder.Append(html.CaptchaImage(CaptchaDefaultHeight, CaptchaDefaultWidth));
                        builder.Append(html.Label(elementName, String.Empty));
                        builder.Append("<br/>");
                        builder.Append(html.CaptchaTextBox(elementName));
                        break;
                    }

                default:
                    break;
            }

            return builder.ToString();
        }
        public static string RenderFile(HtmlHelper html, BootstrapFileModel model)
        {
            if (model == null || string.IsNullOrEmpty(model.htmlFieldName)) return null;

            string validationMessage = "";
            if (model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }
            if (model.tooltipConfiguration != null) model.htmlAttributes.AddRange(model.tooltipConfiguration.ToDictionary());
            var mergedHtmlAttrs = model.htmlAttributes.FormatHtmlAttributes().AddOrReplace("type", "File");
            if (!string.IsNullOrEmpty(model.id)) mergedHtmlAttrs.AddOrReplace("id", model.id);
            return html.TextBox(model.htmlFieldName, null, mergedHtmlAttrs).ToHtmlString() + validationMessage;
        }
Example #4
0
        /// <summary>
        /// Create full captcha
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        internal static MvcHtmlString GenerateFullCaptcha(HtmlHelper htmlHelper, int length)
        {
            var encryptorModel = GetEncryptorModel();
            var captchaText = RandomText.Generate(length);
            var encryptText = Encryption.Encrypt(captchaText, encryptorModel.Password, encryptorModel.Salt);

            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
            var url = urlHelper.Action("Create", "CaptchaImage", new { encryptText});

            var ajax = new AjaxHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer);
            var refresh = ajax.ActionLink("Refresh", "NewCaptcha", "CaptchaImage", new {l = length},
                                          new AjaxOptions { UpdateTargetId = "CaptchaDeText", OnSuccess = "Success" });

            return MvcHtmlString.Create(string.Format(CaptchaFormat, url, htmlHelper.Hidden("CaptchaDeText", encryptText)) +
                                         refresh.ToHtmlString() + " <br/>Enter symbol: " +
                                        htmlHelper.TextBox("CaptchaInputText"));
        }
Example #5
0
        private static MvcHtmlString AutocompleteTextBox(HtmlHelper helper, EntityLine entityLine)
        {
            if (!entityLine.Autocomplete)
            {
                return(helper.FormControlStatic(entityLine, entityLine.Compose(EntityBaseKeys.ToStr), null, null));
            }

            var htmlAttr = new Dictionary <string, object>
            {
                { "class", "form-control sf-entity-autocomplete" },
                { "autocomplete", "off" },
            };

            if (entityLine.PlaceholderLabels)
            {
                htmlAttr.Add("placeholder", entityLine.LabelText);
            }

            return(helper.TextBox(
                       entityLine.Compose(EntityBaseKeys.ToStr),
                       null,
                       htmlAttr));
        }
Example #6
0
        public static MvcHtmlString TextBoxSearchFilter(this HtmlHelper helper, string name, string placeholder, string action, string controllerName, object routeValues, string resultDiv)
        {
            var urlHelper           = new UrlHelper(helper.ViewContext.RequestContext);
            RouteValueDictionary rv = new RouteValueDictionary(routeValues);

            rv = rv.Merge(new
            {
                @class      = "pull-right clearable",
                onkeyup     = "ASE.SearchTextBox(this)",
                onkeypress  = "ASE.SearchTextBox(this)",
                placeholder = placeholder,
                data        = String.Format("#{0}", resultDiv ?? "data"),
                onfocus     = "this.value = this.value;",
                isSelect    = helper.ViewContext.RequestContext.HttpContext.Request.Params["isSelect"],
                href        = urlHelper.Action(action, controllerName, helper.ViewContext.RouteData.Values)
            });

            return(helper.TextBox(
                       "searchTB_" + name,
                       helper.ViewContext.HttpContext.Request.Params.AllKeys.Contains("searchTB_" + name) ? helper.ViewContext.HttpContext.Request.Params["searchTB_" + name] : "",
                       rv
                       ));
        }
        public static MvcHtmlString CustomComboBoxFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string entityTypeLookup, object htmlAttributes = null, string placeHolderString = "", string index = "")
        {
            var    metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string value    = metadata.Model == null ? string.Empty : metadata.Model.ToString();

            value = Convert.ToInt32(value) > 0 ? value : string.Empty;
            //Note Temporary Fixed For not nullable guid.
            //if (value == Guid.Empty.ToString()) value = string.Empty;
            string fieldId = metadata.PropertyName;

            var attributes = htmlAttributes == null ? new RouteValueDictionary() : new RouteValueDictionary(htmlAttributes);

            attributes["service"]         = entityTypeLookup;
            attributes["controltype"]     = "kendoComboBox";
            attributes["serverFiltering"] = false.ToString();
            attributes["placeHolder"]     = placeHolderString == "" ? PlaceHolder : placeHolderString;
            attributes["customType"]      = "text";
            attributes["id"]   = fieldId + index;
            attributes["name"] = fieldId;
            var combox = helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes).ToString();

            return(new MvcHtmlString(combox));
        }
        /// <summary>
        /// Returns a textbox for DateTime model properties
        /// </summary>
        /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
        /// <param name="expression">An expression that contains the property to render</param>
        /// <param name="name">The property name which the value must be set</param>
        public static MvcHtmlString DateTimeFor <TModel, TDateTime>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TDateTime> > expression, string name)
        {
            var    metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            object dateValue;

            if (metadata.Model is DateTime? || metadata.Model == null)
            {
                dateValue = metadata.Model != null && (metadata.Model as DateTime?).HasValue ? (metadata.Model as DateTime?).Value.ToShortDateString() : string.Empty;
            }
            else
            {
                dateValue = Convert.ToDateTime(ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model).ToShortDateString();
            }

            if (String.IsNullOrEmpty(name))
            {
                name = ExpressionHelper.GetExpressionText(expression);
            }

            var datetimefor = htmlHelper.TextBox(name, dateValue).ToHtmlString();

            return(MvcHtmlString.Create(datetimefor));
        }
        private static IHtmlString CaptchaHelper(this HtmlHelper htmlHelper, string name, string routeName, string actionName, string controllerName, object routeValues, string refreshLabel, object htmlAttributes)
        {
            TagBuilder tagBuilder1 = new TagBuilder("div");

            tagBuilder1.MergeAttribute("class", "captchaContainer");
            TagBuilder tagBuilder2 = new TagBuilder("img");

            tagBuilder2.MergeAttribute("src", UrlHelper.GenerateUrl(routeName, actionName, controllerName, (RouteValueDictionary)routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true));
            tagBuilder2.MergeAttribute("border", "0");
            TagBuilder tagBuilder3 = new TagBuilder("a");

            tagBuilder3.MergeAttribute("href", "javascript:void(0)");
            tagBuilder3.MergeAttribute("class", "newCaptcha");
            tagBuilder3.SetInnerText(refreshLabel);
            MvcHtmlString mvcHtmlString = htmlHelper.TextBox(name, "", htmlAttributes);
            var           sb            = new StringBuilder();

            sb.Append(mvcHtmlString);
            sb.Append(tagBuilder2.ToString(TagRenderMode.Normal));
            sb.Append(tagBuilder3.ToString(TagRenderMode.Normal));
            tagBuilder1.InnerHtml = sb.ToString();
            return(new HtmlString(tagBuilder1.ToString(TagRenderMode.Normal)));
        }
Example #10
0
        private static MvcHtmlString CreateAutocomplete <TModel, TValue>(HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string actionUrl, string placeholder, bool?isRequired)
        {
            var attributes = new Dictionary <string, object>
            {
                { "data-autocomplete", true },
                { "data-action", actionUrl }
            };

            if (!string.IsNullOrWhiteSpace(placeholder))
            {
                attributes.Add("placeholder", placeholder);
            }

            if (isRequired.HasValue && isRequired.Value)
            {
                attributes.Add("required", "required");
            }

            Func <TModel, TValue> method = expression.Compile();
            // These bits are commented out as we don't need them - our box has the same value as label
//			var value = method(helper.ViewData.Model);
            var baseProperty = ((MemberExpression)expression.Body).Member.Name;
//			var hidden = helper.Hidden(baseProperty, value);

//			attributes.Add("data-value-name", baseProperty);

//			var autocompleteName = baseProperty + "_autocomplete";
//			var textBox = helper.TextBox(autocompleteName, null, string.Empty, attributes);
            var textBox = helper.TextBox(baseProperty, null, string.Empty, attributes);

            var builder = new StringBuilder();

//			builder.AppendLine(hidden.ToHtmlString());
            builder.AppendLine(textBox.ToHtmlString());

            return(new MvcHtmlString(builder.ToString()));
        }
        public static MvcHtmlString CustomComboxBoxLinkedWithCascadeFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string entityTypeLookup, Expression <Func <TModel, TValue> > cascadeFromExpression, string customActionCascade, string controller, object htmlAttributes = null)
        {
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var url       = urlHelper.Action(customActionCascade, controller);

            var    metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string value    = metadata.Model == null ? string.Empty : metadata.Model.ToString();

            value = Convert.ToInt32(value) > 0 ? value : string.Empty;

            var    cascadeFromMetadata = ModelMetadata.FromLambdaExpression(cascadeFromExpression, helper.ViewData);
            string cascadeFromValue    = cascadeFromMetadata.Model == null ? string.Empty : cascadeFromMetadata.Model.ToString();

            cascadeFromValue = Convert.ToInt32(cascadeFromValue) > 0 ? cascadeFromValue : string.Empty;
            //Note Temporary Fixed For not nullable guid.
            //if (value == Guid.Empty.ToString()) value = string.Empty;
            //if (cascadeFromValue == Guid.Empty.ToString()) value = string.Empty;

            string fieldId     = metadata.PropertyName;
            string cascadeFrom = cascadeFromMetadata.PropertyName;

            var attributes = htmlAttributes == null ? new RouteValueDictionary() : new RouteValueDictionary(htmlAttributes);

            attributes["service"]          = entityTypeLookup;
            attributes["controltype"]      = "kendoComboBoxLinkedWithCascade";
            attributes["serverFiltering"]  = false;
            attributes["placeHolder"]      = PlaceHolder;
            attributes["customType"]       = "text";
            attributes["cascadeFrom"]      = cascadeFrom;
            attributes["cascadeFromValue"] = cascadeFromValue;
            attributes["urlCascade"]       = url;
            attributes["id"]   = fieldId;
            attributes["name"] = fieldId;
            var combox = helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes).ToString();

            return(new MvcHtmlString(combox));
        }
        public static MvcHtmlString CustomComboBoxWithCustomDataLinkedFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string action, string controller, Expression <Func <TModel, int?> > cascadeFromExpression, string placeHolderString = "", params string[] paramControls)
        {
            var    urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var    url       = urlHelper.Action(action, controller);
            var    metadata  = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string value     = metadata.Model == null ? string.Empty : metadata.Model.ToString();
            string fieldId   = metadata.PropertyName;

            var    cascadeFromMetadata = ModelMetadata.FromLambdaExpression(cascadeFromExpression, helper.ViewData);
            string cascadeFromValue    = cascadeFromMetadata.Model == null ? string.Empty : cascadeFromMetadata.Model.ToString();

            cascadeFromValue = Convert.ToInt32(cascadeFromValue) > 0 ? cascadeFromValue : string.Empty;
            string cascadeFrom = cascadeFromMetadata.PropertyName;

            //Note Temporary Fixed For not nullable guid.
            //if (value == Guid.Empty.ToString()) value = string.Empty;
            //if (cascadeFromValue == Guid.Empty.ToString()) value = string.Empty;

            //Note Temporary Fixed For not nullable guid.
            //if (value == Guid.Empty.ToString()) value = string.Empty;

            var attributes = new RouteValueDictionary();

            attributes["controltype"]      = "kendoComboBoxForCustomDataLinkedFor";
            attributes["serverFiltering"]  = false.ToString();
            attributes["url"]              = url;
            attributes["placeHolder"]      = placeHolderString == "" ? PlaceHolder : placeHolderString;
            attributes["customType"]       = "text";
            attributes["cascadeFrom"]      = cascadeFrom;
            attributes["parameter"]        = cascadeFrom + "," + string.Join(",", paramControls);
            attributes["cascadeFromValue"] = cascadeFromValue;
            attributes["id"]   = fieldId;
            attributes["name"] = fieldId;
            var combox = helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes).ToString();

            return(new MvcHtmlString(combox));
        }
Example #13
0
        private static string GenerateDateTimePickerDiv(HtmlHelper htmlHelper, string datePickerIndentity, string name, object value, DateTimeCategory category, CustomizeDateTimePicker customize, IDictionary <string, object> htmlAttributes)
        {
            var divTag = new TagBuilder("div");

            divTag.MergeAttribute("id", datePickerIndentity);
            divTag.AddCssClass(CustomizeDateTimePicker.GetDateTimePickerCssClass(category));
            divTag.MergeAttribute("data-date-format", CustomizeDateTimePicker.DateTimePickerFormatsDictionary[category]);
            divTag.MergeAttribute("data-link-format", CustomizeDateTimePicker.DateTimePickerFormatsDictionary[category]);
            divTag.MergeAttribute("data-link-field", name);
            //divTag.MergeAttribute("data-date", value);

            var dateTextbox = htmlHelper.TextBox(name, CustomizeDateTimePicker.ConvertValueFormat(value, category), customize.GetDateTextBoxAttributes(htmlAttributes));

            var firstSpan = new TagBuilder("span");

            firstSpan.AddCssClass(CustomizeDateTimePicker.IconSpanCss);
            var removeSpan = new TagBuilder("span");

            removeSpan.AddCssClass(CustomizeDateTimePicker.RemoveIcon);

            var secondSpan = new TagBuilder("span");

            secondSpan.AddCssClass(CustomizeDateTimePicker.IconSpanCss);
            var addSpan = new TagBuilder("span");

            addSpan.AddCssClass(CustomizeDateTimePicker.AddIconsDictionary[category]);

            firstSpan.InnerHtml  = removeSpan.ToString(TagRenderMode.Normal);
            secondSpan.InnerHtml = addSpan.ToString(TagRenderMode.Normal);

            var script = GenerateDateTimePickerScript(datePickerIndentity, category, customize);

            divTag.InnerHtml = dateTextbox.ToHtmlString() + firstSpan.ToString(TagRenderMode.Normal) +
                               secondSpan.ToString(TagRenderMode.Normal) + script;

            return(divTag.ToString(TagRenderMode.Normal));
        }
Example #14
0
        protected override void ProcessCore(TagHelperContext context, TagHelperOutput output)
        {
            // TODO: (mh) (core) This is not how model expressions work. "value" is just the value,
            // but where is the name/id of the control? You can't just pass null to HtmlHelper.TextBox(),
            // you need a name. TBD with MC. Also: expecting an attribute named "value" without declaring a public property
            // for it in this class is really BAD API design!
            string value;

            if (output.Attributes.TryGetAttribute("value", out var valueAttribute))
            {
                value = valueAttribute.Value.ToString();
            }
            else
            {
                value = For != null?For.Model.ToString() : string.Empty;
            }

            var defaultColor = DefaultColor.EmptyNull();
            var isDefault    = value.EqualsNoCase(defaultColor);

            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.AppendCssClass("input-group colorpicker-component sm-colorbox");
            output.Attributes.Add("data-fallback-color", defaultColor);

            output.Content.AppendHtml(HtmlHelper.TextBox(For != null ? For.Name : string.Empty,
                                                         isDefault ? string.Empty : value,
                                                         new { @class = "form-control colorval", placeholder = defaultColor }));

            var addon = new TagBuilder("div");

            addon.AddCssClass("input-group-append input-group-addon");
            addon.InnerHtml.AppendHtml(
                $"<div class='input-group-text'><i class='thecolor' style='{(DefaultColor.HasValue() ? "background-color: " + DefaultColor : string.Empty)}'>&nbsp;</i></div>");

            output.Content.AppendHtml(addon);
        }
Example #15
0
        public static MvcHtmlString CustomNumericTextBoxFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string formatString, object htmlAttributes, int minimumValue, int decimals)
        {
            var    metadata   = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string value      = metadata.Model == null ? string.Empty : metadata.Model.ToString();
            var    attributes = new RouteValueDictionary(htmlAttributes);

            attributes["controltype"] = "kendoNumericTextBox";
            attributes["min"]         = minimumValue;
            attributes["max"]         = Int64.MaxValue;
            attributes["decimals"]    = decimals;

            if (formatString != null && formatString.Trim() != string.Empty)
            {
                attributes["format"] = formatString;
            }
            else
            {
                if (decimals > 0)
                {
                    StringBuilder sb = new StringBuilder(decimals);

                    sb.Append("#,##0.");
                    for (int i = 0; i < decimals; i++)
                    {
                        sb.Append("0");
                    }

                    attributes["format"] = sb.ToString();
                }
                else
                {
                    attributes["format"] = "#,##0";
                }
            }

            return(helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes));
        }
        public static MvcHtmlString TextBoxCalendar(this HtmlHelper htmlHelper, string id, string valor, EnumTipoCalendarios tipocalendario = EnumTipoCalendarios.SoloFecha,
                                                    RouteValueDictionary htmlAttributes = null)
        {
            var sb = new StringBuilder();

            sb.AppendLine(@"    <div class=""input-group date datepicker"" id=""{0}"">
        {1}
        <span class=""input-group-addon add-on""><span class=""glyphicon glyphicon-calendar""></span></span>
        </div>");

            if (htmlAttributes == null)
            {
                htmlAttributes = new RouteValueDictionary {
                    { "size", 16 }, { "class", "form-control" }
                };
            }
            else
            {
                if (!htmlAttributes.ContainsKey("size"))
                {
                    htmlAttributes.Add("size", 16);
                }

                if (!htmlAttributes.ContainsKey("class"))
                {
                    htmlAttributes.Add("class", "form-control");
                }
                else
                {
                    htmlAttributes["class"] = htmlAttributes["class"] + " form-control";
                }
            }

            MvcHtmlString html = htmlHelper.TextBox(id, valor, htmlAttributes);

            return(new MvcHtmlString(String.Format(sb.ToString(), id, html)));
        }
        public static MvcHtmlString CustomMaskedTextBoxFor <TModel, TValue>(this HtmlHelper <TModel> helper,
                                                                            Expression <Func <TModel, TValue> > expression, String maskFormat, object htmlAttributes)
        {
            var    metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            String value    = metadata.Model == null ? String.Empty : metadata.Model.ToString();

            var attributes = new RouteValueDictionary(htmlAttributes);

            attributes["id"]           = metadata.PropertyName;
            attributes["name"]         = metadata.PropertyName;
            attributes["autocomplete"] = "off";
            attributes["controltype"]  = "kendoMaskedTextBox";

            if (String.IsNullOrEmpty(maskFormat))
            {
                attributes["mask"] = "000-000-000-000";
            }
            else
            {
                attributes["mask"] = maskFormat;
            }

            return(helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes));
        }
Example #18
0
 public static MvcHtmlString Editor <TModel>(this HtmlHelper <TModel> htmlHelper, ModelMetadata metadata, IDictionary <string, object> htmlAttributes = null)
 {
     //.Set("placeholder", metadata.DisplayName)
     if (!string.IsNullOrWhiteSpace(metadata.TemplateHint))
     {
         return(htmlHelper.Editor(metadata.PropertyName, metadata.TemplateHint, null, new { htmlAttributes }));
     }
     else if (metadata.IsReadOnly)
     {
         return(htmlHelper.ReadOnly(metadata.Model, htmlAttributes));
     }
     else if (metadata.ModelType == typeof(bool) || metadata.ModelType == typeof(bool?))
     {
         return(htmlHelper.CheckBox(metadata.PropertyName, (bool?)metadata.Model == true));
     }
     else if (metadata.PropertyName == "Password")
     {
         return(htmlHelper.Password(metadata.PropertyName, metadata.Model, htmlAttributes));
     }
     else
     {
         return(htmlHelper.TextBox(metadata.PropertyName, metadata.Model, htmlAttributes));
     }
 }
Example #19
0
        public static MvcHtmlString PSIntBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
        {
            var newAttributes = ControlHelper.GetHtmlAttributes(htmlAttributes);

            newAttributes = newAttributes
                            .AddClass("class", "touchspin .ps-int-box form-control")
                            .AddClass("maxlength", "8");

            string textBoxString = htmlHelper.TextBox(name, value, newAttributes).ToHtmlString();
            string jsFunction    = @" <script type=""text/javascript"">
			$(document).ready(function()
			{
				$('.touchspin').TouchSpin({
							buttondown_class: 'btn btn-white',
					buttonup_class:
							'btn btn-white'
				});
					});
		</script>"        ;

            textBoxString += jsFunction;

            return(new MvcHtmlString(textBoxString));
        }
Example #20
0
        public static MvcHtmlString DatePicker(this HtmlHelper html, string id, string value, string validationMessage,
                                               object htmlAttributes = null, bool isDisabled = false, bool isReadonly = false)
        {
            Dictionary <string, object> attr = new Dictionary <string, object>();

            attr.Add("class", "datepicker");
            if (isReadonly)
            {
                attr.Add("readonly", isReadonly);
            }

            if (htmlAttributes != null)
            {
                PropertyInfo[] props = htmlAttributes.GetType().GetProperties();
                foreach (var prop in props)
                {
                    attr.Add(prop.Name, prop.GetValue(htmlAttributes, null));
                }
            }

            var result = html.TextBox(id, value, attr).ToString();

            return(new MvcHtmlString(result));
        }
Example #21
0
        public static string DateTimeInput(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes)
        {
            string displayValue = null;

            if (value != null)
            {
                DateTime theDateTime = Convert.ToDateTime(value);
                displayValue = theDateTime.ToShortDateString() + " " + theDateTime.ToShortTimeString();
            }
            StringBuilder sb = new StringBuilder();

            sb.Append(GetDateInputScripts(htmlHelper));
            sb.Append(htmlHelper.TextBox(name, displayValue, htmlAttributes));
            sb.Append("<script type=\"text/javascript\">");
            sb.Append(@"
				$(document).ready(function() {
					$('#"                     + name + @"').dynDateTime({
						showsTime: 'true',
						ifFormat : '"                         + ConvertDateFormat(CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern) + " " + ConvertTimeFormat(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern) + @"'
					});
				})"                );
            sb.Append("</script>");
            return(sb.ToString());
        }
Example #22
0
        private static MvcHtmlString InternalEntityStrip <T>(this HtmlHelper helper, EntityStrip entityStrip)
        {
            if (!entityStrip.Visible || entityStrip.HideIfNull && entityStrip.UntypedValue == null)
            {
                return(MvcHtmlString.Empty);
            }


            HtmlStringBuilder sb = new HtmlStringBuilder();

            using (sb.SurroundLine(new HtmlTag("div", entityStrip.Prefix).Class("SF-entity-strip SF-control-container")))
            {
                sb.AddLine(helper.Hidden(entityStrip.Compose(EntityListBaseKeys.ListPresent), ""));

                using (sb.SurroundLine(new HtmlTag("div", entityStrip.Compose("hidden")).Class("hide")))
                {
                }

                using (sb.SurroundLine(new HtmlTag("ul", entityStrip.Compose(EntityStripKeys.ItemsContainer))
                                       .Class("sf-strip").Class(entityStrip.Vertical ? "sf-strip-vertical" : "sf-strip-horizontal")))
                {
                    if (entityStrip.UntypedValue != null)
                    {
                        foreach (var itemTC in TypeContextUtilities.TypeElementContext((TypeContext <MList <T> >)entityStrip.Parent))
                        {
                            sb.Add(InternalStripElement(helper, itemTC, entityStrip));
                        }
                    }

                    using (sb.SurroundLine(new HtmlTag("li").Class("sf-strip-input input-group")))
                    {
                        if (entityStrip.Autocomplete)
                        {
                            var htmlAttr = new Dictionary <string, object>
                            {
                                { "class", "sf-entity-autocomplete" },
                                { "autocomplete", "off" },
                            };

                            sb.AddLine(helper.TextBox(
                                           entityStrip.Compose(EntityBaseKeys.ToStr),
                                           null,
                                           htmlAttr));
                        }

                        using (sb.SurroundLine(new HtmlTag("span", entityStrip.Compose("shownButton"))))
                        {
                            sb.AddLine(EntityButtonHelper.Create(helper, entityStrip, btn: false));
                            sb.AddLine(EntityButtonHelper.Find(helper, entityStrip, btn: false));
                        }
                    }
                }

                if (entityStrip.ElementType.IsEmbeddedEntity() && entityStrip.Create)
                {
                    T embeddedEntity = (T)(object)new ConstructorContext(helper.ViewContext.Controller).ConstructUntyped(typeof(T));
                    TypeElementContext <T> templateTC = new TypeElementContext <T>(embeddedEntity, (TypeContext)entityStrip.Parent, 0, null);
                    sb.AddLine(EntityBaseHelper.EmbeddedTemplate(entityStrip, EntityBaseHelper.RenderPopup(helper, templateTC, RenderPopupMode.Popup, entityStrip, isTemplate: true), null));
                }

                sb.AddLine(entityStrip.ConstructorScript(JsModule.Lines, "EntityStrip"));
            }

            return(helper.FormGroup(entityStrip, entityStrip.Prefix, entityStrip.LabelHtml ?? entityStrip.LabelText.FormatHtml(), sb.ToHtml()));
        }
Example #23
0
 /// <summary>
 /// Create full captcha
 /// </summary>
 /// <param name="htmlHelper"></param>
 /// <param name="text"></param>
 /// <param name="inputText"></param>
 /// <param name="length"></param>
 /// <returns></returns>
 internal static MvcHtmlString GenerateFullCaptcha(HtmlHelper htmlHelper, string text, string inputText, int length)
 {
     var encryptorModel = GetEncryptorModel();
     var captchaText = RandomText.Generate(length);
     var encryptText = GetEncryption().Encrypt(captchaText, encryptorModel.Password, encryptorModel.Salt);
     var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
     var url = urlHelper.Action("Create", "CaptchaImage", new { encryptText });
     var ajax = new AjaxHelper(htmlHelper.ViewContext, htmlHelper.ViewDataContainer);
     var refresh = ajax.ActionLink(text, "NewCaptcha", "CaptchaImage", new { l = length },
                                                                 new AjaxOptions { UpdateTargetId = "CaptchaDeText", OnSuccess = "Success" });
     string tgs = "<div style=\"float: left; margin-top: 5px;\">" + refresh.ToHtmlString() + " <br/>" + inputText + "<br/>" +
         htmlHelper.TextBox("CaptchaInputText", "", new { data_val_required = "*", data_val = "true", data_val_length_min = "5", data_val_length_max = "5", data_val_length = "*" }) +
         htmlHelper.ValidationMessage("CaptchaInputText") + "</div>";
     return MvcHtmlString.Create(tgs + string.Format(CaptchaFormat, url, htmlHelper.Hidden("CaptchaDeText", encryptText)));
 }
Example #24
0
        public static MvcHtmlString SplittDateTimeFor <TModel>(
            this HtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, Nullable <DateTime> > > expression, bool useTemplate = false, string templateName = null)
        {
            var fullPropertyPath =
                htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(
                    ExpressionHelper.GetExpressionText(expression));

            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }

            Nullable <DateTime> date = null;

            try
            {
                date = expression.Compile().Invoke(htmlHelper.ViewData.Model);
            }
            catch
            {
            }
            string Year;
            string Month;
            string Day;

            if (!date.HasValue || date.Value != default(DateTime))
            {
                Year  = string.Empty;
                Month = string.Empty;
                Day   = string.Empty;
            }
            else
            {
                Year  = date.Value.Year.ToString();
                Month = date.Value.Month.ToString();
                Day   = date.Value.Day.ToString();
            }
            TestDateTimeDisplay displayModel = new TestDateTimeDisplay();

            displayModel.ImportFromModel(date, null);

            if (useTemplate)
            {
                if (templateName == null)
                {
                    templateName = typeof(TestDateTimeDisplay).Name;
                }
                ViewDataDictionary <TestDateTimeDisplay> dataDictionary = new ViewDataDictionary <TestDateTimeDisplay>(displayModel);
                dataDictionary.TemplateInfo.HtmlFieldPrefix = fullPropertyPath + ".$";
                string res =
                    BasicHtmlHelper.RenderDisplayInfo(htmlHelper, typeof(TestDateTimeDisplay), fullPropertyPath) +
                    htmlHelper.Partial(templateName, dataDictionary);
                return(MvcHtmlString.Create(res));
            }
            else
            {
                string res =
                    BasicHtmlHelper.RenderDisplayInfo(htmlHelper, typeof(TestDateTimeDisplay), fullPropertyPath) +
                    htmlHelper.TextBox(fullPropertyPath + ".$.Year", Year, new { style = "text-align:right" }).ToString() + htmlHelper.ValidationMessage(fullPropertyPath + ".Year", "*") + "&nbsp;" +
                    htmlHelper.TextBox(fullPropertyPath + ".$.Month", Month, new { style = "text-align:right" }).ToString() + htmlHelper.ValidationMessage(fullPropertyPath + ".Month", "*") + "&nbsp;" +
                    htmlHelper.TextBox(fullPropertyPath + ".$.Day", Day, new { style = "text-align:right" }).ToString() + htmlHelper.ValidationMessage(fullPropertyPath + ".Day", "*") + "&nbsp;";

                return(MvcHtmlString.Create(res));
            }
        }
Example #25
0
 public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper, string name, object htmlAttributes = null, object value = null, string format = null)
 {
     return(htmlHelper.TextBox(name, value, format, htmlAttributes));
 }
Example #26
0
        public virtual MvcHtmlString Render()
        {
            string id = ExpressionHelper.GetExpressionText(_expression);

            if (_prefetch)
            {
                if (_mode == CustomComboBoxMode.Search)
                {
                    throw new ArgumentException("Cannot use Prefetch in Search mode");
                }

                if (_enablePaging)
                {
                    throw new ArgumentException("Cannot use Prefetch with Paging");
                }
            }

            #region Init javascript
            var sb = new StringBuilder();
            sb.AppendFormat("<script language='javascript'>");
            sb.AppendFormat("$().ready(function() {{");
            sb.AppendLine();
            sb.AppendFormat("$('#{0}').customComboBox({{", string.IsNullOrEmpty(_inputName) ? id + "-autocomplete" : _inputName);
            sb.AppendFormat("mode : {0}, ", (int)_mode);

            if (_advancedSearchSetting != null && _advancedSearchSetting.Enable)
            {
                sb.AppendFormat("advancedSearchOptions: '{0}', ", new JavaScriptSerializer().Serialize(_advancedSearchSetting));
            }

            if (_addSetting != null && _addSetting.Enable)
            {
                sb.AppendFormat("addOptions: '{0}', ", new JavaScriptSerializer().Serialize(_addSetting));
                sb.AppendFormat("addMode: {0}, ", (int)_addMode);
                sb.AppendFormat("addHintChars: {0}, ", _addHintCharacters);
            }

            if (_localData != null)
            {
                sb.AppendFormat("source: {0},", new JavaScriptSerializer().Serialize(_localData));
                _prefetch = true;
            }
            else
            {
                sb.AppendFormat("url: '{0}', ", _ajaxUrl);
                if (_initData != null)
                {
                    sb.AppendFormat("initData: {0},", new JavaScriptSerializer().Serialize(_initData));
                }
            }

            sb.AppendFormat("prefetch: {0}, ", _prefetch ? "true" : "false");

            if (!string.IsNullOrEmpty(_onChanged))
            {
                sb.AppendFormat("onChanged: '{0}', ", _onChanged);
            }

            if (!string.IsNullOrEmpty(_onSelect))
            {
                sb.AppendFormat("onSelected: '{0}', ", _onSelect);
            }

            if (!string.IsNullOrEmpty(_onDropdown))
            {
                sb.AppendFormat("onDropdown: '{0}', ", _onDropdown);
            }

            if (_containerMaxHeight > 0)
            {
                sb.AppendFormat("maxHeight: '{0}', ", _containerMaxHeight);
            }

            sb.AppendFormat("enableCaching: {0}, ", _enableCaching ? "true" : "false");
            if (_inputWidth > 0)
            {
                sb.AppendFormat("inputWidth: {0}, ", _inputWidth);
            }

            sb.AppendFormat("enableColumns: {0}, ", _enableColumns ? "true" : "false");
            sb.AppendFormat("headers: {0}, ", new JavaScriptSerializer().Serialize(_headers));
            sb.AppendFormat("enablePaging: {0}, ", _enablePaging ? "true" : "false");
            sb.AppendFormat("pageSize: {0}, ", _pageSize);
            sb.AppendFormat("loadMoreText: '{0}', ", _loadMoreText);
            sb.AppendFormat("hiddenId: '{0}' ", id);
            sb.AppendFormat("}});");
            sb.AppendLine();
            sb.AppendFormat("  }});");
            sb.AppendFormat("</script>");
            #endregion

            string classAttValues = string.Empty;
            if (_attributes.ContainsKey("class") && _attributes["class"] != null)
            {
                classAttValues = _attributes["class"].ToString();
                _attributes.Remove("class");
            }

            classAttValues = string.Format("{0} {1}", classAttValues, "t-autocomplete");
            if (!string.IsNullOrEmpty(classAttValues))
            {
                _attributes.Add("class", classAttValues);
            }
            _attributes.Add("data-init-value", GetDefaultDataValue(_expression.Body.Type));

            var input = _helper.TextBox(string.IsNullOrEmpty(_inputName) ? string.Format("{0}-autocomplete", id) : _inputName, string.Empty, _attributes);
            return(MvcHtmlString.Create(string.Format("{0}{1}{2}", input, _helper.HiddenFor(_expression, new { @class = classAttValues }), sb)));
        }
Example #27
0
 public override MvcHtmlString ProcessTag(HtmlHelper htmlHelper, IContext context, string content, object[] parms)
 {
     return(htmlHelper.TextBox(parms[0].ToString()));
 }
Example #28
0
        private static MvcHtmlString DatePickerForParameter(HtmlHelper htmlHelper, ReportParameter reportParameter, bool disabled)
        {
            Dictionary<string, object> htmlAttributes = GetHtmlAttributes(reportParameter.Dependents, null, disabled);
            htmlAttributes.Add("class", "datepicker");

            return htmlHelper.TextBox(reportParameter.Id, reportParameter.CurrentValue, htmlAttributes);
        }
Example #29
0
        /// <summary>Generate a control for a set preference.</summary>
        private static string SetPreferenceControl(HtmlHelper helper, MetaAttribute ma, Preference preference)
        {
            string result;

            if (ma.HasChoices)
            {
                if (preference != null)
                {
                    MultiSelectList listData = new MultiSelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text",
                        SelectHelper.ValuesFromValueSet(preference.Set));
                    result = helper.ListBox(ma.PreferenceSetControlName, listData);
                }
                else
                {
                    MultiSelectList listData = new MultiSelectList(SelectHelper.DropDownRecordsFromValueSet(ma.ChoicesCollection), "Value", "Text");
                    result = helper.ListBox(ma.PreferenceSetControlName, listData);
                }
            }
            else
            {
                if (preference != null)
                {
                    result = helper.TextBox(ma.PreferenceSetControlName, preference.RawValues);
                }
                else
                {
                    result = helper.TextBox(ma.PreferenceSetControlName);
                }
            }
            return result;
        }
 /// <summary>
 /// Renders the specified HTML.
 /// </summary>
 /// <param name="html">The HTML helper.</param>
 /// <param name="name">The element name.</param>
 /// <param name="value">The element value.</param>
 /// <param name="values">The element values.</param>
 /// <returns>Returns element html code.</returns>
 public override string Render(HtmlHelper html, String name, String value, String values)
 {
     return html.TextBox(name, value).ToString();
 }
Example #31
0
 public override MvcHtmlString ProcessTag(HtmlHelper htmlHelper, IContext context, string content, object[] parms)
 {
     return htmlHelper.TextBox(parms[0].ToString());
 }
Example #32
0
 private static string NonSelectableAttribute(HtmlHelper helper, MetaAttribute ma, ProductAttribute attribute)
 {
     return (attribute != null)
                 ? helper.TextBox(ma.ProductAttributeHtmlControlName, attribute.ControlFormattedValue)
                 : helper.TextBox(ma.ProductAttributeHtmlControlName);
 }
 public override MvcHtmlString Generate(HtmlHelper htmlHelper, string name, object value)
 {
     return htmlHelper.TextBox(name, value, new { @class = CssClass, style = CssStyle });
 }
Example #34
0
        private static MvcHtmlString TextBoxForParameter(HtmlHelper htmlHelper, ReportParameter reportParameter, bool disabled)
        {
            Dictionary<string, object> htmlAttributes = GetHtmlAttributes(reportParameter.Dependents, reportParameter.Suggestions, disabled);

            return htmlHelper.TextBox(reportParameter.Id, reportParameter.CurrentValue, htmlAttributes);
        }
Example #35
0
        public static MvcHtmlString LookupHtml <TModel, TValue>(this HtmlHelper <TModel> html,
                                                                Expression <Func <TModel, TValue> > expression,
                                                                string controlName, string idFieldName, string textFieldName,
                                                                string actionName, string controllerName, object routeValues,
                                                                string jsonActionName, string jsonControllerName,
                                                                string[] columns = null, string onChange = null, bool isVisible = true, Dictionary <string, string> columnNames = null)
            where TModel : class
            where TValue : class
        {
            ViewDataDictionary <TModel> ViewData = html.ViewData;
            ModelMetadata modelMetaData          = ModelMetadata.FromLambdaExpression <TModel, TValue>(expression, ViewData);

            StringBuilder sbFields  = new StringBuilder();
            UrlHelper     urlHelper = new UrlHelper(html.ViewContext.RequestContext);

            sbFields.Append(html.Hidden(controlName, new { @id = controlName }).ToHtmlString());
            foreach (ModelMetadata m in modelMetaData.Properties)
            {
                if (m.PropertyName != "Created_Date" && m.PropertyName != "Last_Updated_Date")
                {
                    sbFields.Append(html.Hidden(string.Format("{0}.{1}", modelMetaData.PropertyName, m.PropertyName), modelMetaData.Model == null ? "" : typeof(TValue).GetProperty(m.PropertyName).GetValue(modelMetaData.Model, null), new { @id = string.Format("HiddenID_{0}{1}", modelMetaData.PropertyName, m.PropertyName) }).ToHtmlString());
                }
            }
            String displayMode = (isVisible) ? "inline" : "none";

            sbFields.Append(html.TextBox(string.Format("LabelID_{0}", modelMetaData.PropertyName), modelMetaData.Model == null ? "" : typeof(TValue).GetProperty(textFieldName).GetValue(modelMetaData.Model, null), new { @readonly = "readonly", style = "display:" + displayMode + ";" }));
            sbFields.Append(string.Format("<input type=\"button\" value=\"...\" class=\"t-button\" onclick=\"lookupOpenWindow('#SearchWindow_{0}','#SearchWindowGrid_{0}')\" />", modelMetaData.PropertyName));

            sbFields.Append(
                html.Telerik().Window().BuildWindow("SearchWindow_" + modelMetaData.PropertyName)
                .Modal(true).Resizable().Draggable(true)
                .Content(
                    html.Telerik().Grid <TValue>()
                    .Name("SearchWindowGrid_" + modelMetaData.PropertyName)
                    .Selectable()
                    .Columns(cols => {
                if (columns == null)
                {
                    foreach (ModelMetadata m in modelMetaData.Properties)
                    {
                        if (m.ShowForDisplay)
                        {
                            if (columnNames != null && columnNames.Count > 0 && columnNames.ContainsKey(m.PropertyName))
                            {
                                cols.Bound(m.PropertyName).Filterable(true).Title(columnNames[m.PropertyName]);
                            }
                            else
                            {
                                cols.Bound(m.PropertyName).Filterable(true);
                            }
                        }
                    }
                }
                else
                {
                    foreach (string column in columns)
                    {
                        if (columnNames != null && columnNames.Count > 0 && columnNames.ContainsKey(column))
                        {
                            cols.Bound(column).Filterable(true).Title(columnNames[column]);
                        }
                        else
                        {
                            cols.Bound(column).Filterable(true);
                        }
                    }
                }
                cols.Bound(idFieldName).Filterable(false)
                .ClientTemplate("<a href='#' onClick='onLookupMasterSelect(<#= " + idFieldName + " #>, \"#HiddenID_" + modelMetaData.PropertyName + "\", \"#LabelID_" + modelMetaData.PropertyName + "\", \"" + urlHelper.Action(jsonActionName, jsonControllerName) + "\", \"#SearchWindow_" + modelMetaData.PropertyName + "\", \"" + textFieldName + "\", \"" + (onChange ?? "") + "\")'>Select</a>").Title("Select");
            })
                    .DataKeys(keys => keys.Add(idFieldName))
                    .DataBinding(binding => binding.Ajax().Select(actionName, controllerName, routeValues))
                    .Pageable(paging => paging.PageSize(ConfigurationHelper.GetsmARTLookupGridPageSize()).Enabled(true).Total(100))
                    .ClientEvents(events => events.OnDataBinding("LookupGrid_onDataBinding").OnLoad("SetDefaultFilterToContains"))
                    //.ToolBar(commands => commands.Custom().HtmlAttributes(new { id = "refresh", OnClientClick = string.Format("refreshlookupWindow('SearchWindowGrid_{0}',{1},{2},{3})",modelMetaData.PropertyName,controllerName,actionName,routeValues) }).Text("Refresh"))
                    .Filterable()
                    .ToHtmlString()
                    )
                .ClientEvents(events => events.OnClose("closeWindow"))
                .Visible(false).ToHtmlString()

                );

            MvcHtmlString htmlString = MvcHtmlString.Create(sbFields.ToString());

            return(htmlString);
        }
 private static string CreateSettingTextBox(HtmlHelper htmlHelper, string name, object value, int? length)
 {
     IDictionary<string, object> htmlAttributes = new Dictionary<string, object>();
     if (length.HasValue)
     {
         htmlAttributes.Add("style", string.Format("width:{0}px", length.Value));
     }
     return htmlHelper.TextBox(name, value, htmlAttributes);
 }
Example #37
0
        // How to use [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] for @Html.TextBox
        // @Html.TextBoxWithFormatFor(m => m.CustomDate, new Dictionary<string, object> { { "class", "datepicker" } })

        public static MvcHtmlString TextBoxWithFormatFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression, IDictionary <string, object> htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            return(htmlHelper.TextBox(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(metadata.PropertyName), string.Format(metadata.DisplayFormatString, metadata.Model), htmlAttributes));
        }
Example #38
0
 /// <summary>
 /// 呈现控件
 /// </summary>
 public virtual MvcHtmlString Render(HtmlHelper htmlHelper, string name)
 {
     //组装容器
     return htmlHelper.TextBox(name, DefaultDateString, this.ShowTime ? InputWidthTypes.Medium : InputWidthTypes.Short, new RouteValueDictionary(this.ToHtmlAttributes()));
 }
        public static string RenderTextBox(HtmlHelper html, BootstrapTextBoxModel model, bool isPassword)
        {
            if (model == null || string.IsNullOrEmpty(model.htmlFieldName)) return null;

            string combinedHtml = "{0}{1}{2}";

            if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.Add("id", model.id);
            if (model.tooltipConfiguration != null) model.htmlAttributes.AddRange(model.tooltipConfiguration.ToDictionary());
            // assign placeholder class
            if (!string.IsNullOrEmpty(model.placeholder)) model.htmlAttributes.Add("placeholder", model.placeholder);
            // assign size class
            model.htmlAttributes.AddOrMergeCssClass("class", BootstrapHelper.GetClassForInputSize(model.size));
            // build html for input
            var input = isPassword
                ? html.Password(model.htmlFieldName, model.value, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString()
                : html.TextBox(model.htmlFieldName, model.value, model.format, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString();

            // account for appendString, prependString, and AppendButtons
            if (!string.IsNullOrEmpty(model.prependString) ||
                !string.IsNullOrEmpty(model.appendString) ||
                model.prependButtons.Any() ||
                model.appendButtons.Any() ||
                model.iconPrepend != Icons._not_set ||
                model.iconAppend != Icons._not_set ||
                !string.IsNullOrEmpty(model.iconPrependCustomClass) ||
                !string.IsNullOrEmpty(model.iconAppendCustomClass))
            {
                TagBuilder appendPrependContainer = new TagBuilder("div");
                string addOnPrependString = "";
                string addOnAppendString = "";
                string addOnPrependButtons = "";
                string addOnAppendButtons = "";
                string addOnPrependIcon = "";
                string addOnAppendIcon = "";

                TagBuilder addOn = new TagBuilder("span");
                addOn.AddCssClass("add-on");
                if (!string.IsNullOrEmpty(model.prependString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    addOn.InnerHtml = model.prependString;
                    addOnPrependString = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.appendString))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    addOn.InnerHtml = model.appendString;
                    addOnAppendString = addOn.ToString();
                }
                if (model.prependButtons.Count() > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    model.prependButtons.ForEach(x => addOnPrependButtons += x.ToHtmlString());
                }
                if (model.appendButtons.Count() > 0)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    model.appendButtons.ForEach(x => addOnAppendButtons += x.ToHtmlString());
                }
                if (model.iconPrepend != Icons._not_set)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    addOn.InnerHtml = new BootstrapIcon(model.iconPrepend, model.iconPrependIsWhite).ToHtmlString();
                    addOnPrependIcon = addOn.ToString();
                }
                if (model.iconAppend != Icons._not_set)
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    addOn.InnerHtml = new BootstrapIcon(model.iconAppend, model.iconAppendIsWhite).ToHtmlString();
                    addOnAppendIcon = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.iconPrependCustomClass))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-prepend");
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconPrependCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnPrependIcon = addOn.ToString();
                }
                if (!string.IsNullOrEmpty(model.iconAppendCustomClass))
                {
                    appendPrependContainer.AddOrMergeCssClass("input-append");
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconAppendCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnAppendIcon = addOn.ToString();
                }

                appendPrependContainer.InnerHtml = addOnPrependButtons + addOnPrependIcon + addOnPrependString + "{0}" + addOnAppendString + addOnAppendIcon + addOnAppendButtons;
                combinedHtml = appendPrependContainer.ToString(TagRenderMode.Normal) + "{1}{2}";
            }

            string helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            string validationMessage = "";
            if(model.displayValidationMessage)
            {
                string validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            return MvcHtmlString.Create(string.Format(combinedHtml, input, validationMessage, helpText)).ToString();
        }
Example #40
0
        private static void AppendRows(HtmlHelper html, TagBuilder tag, List <PropertyInfo> properties, dynamic items, string fieldName, Dictionary <string, IDictionary <string, object> > propertyAttributes, Dictionary <string, IDictionary <string, string> > formattingAttributes)
        {
            for (int i = 0; i < items.Count; i++)
            {
                var fName = fieldName + "[" + i + "].";

                var tr = new TagBuilder("tr");
                tr.Attributes.Add("class", "table-list-mvc-item-view");
                tr.Attributes.Add("data-item-index", i.ToString());

                var allowModify = (bool)properties.FirstOrDefault(p => p.Name.ToLower() == nameof(TableListItem.TL_AllowModify).ToLower()).GetValue((TableListItem)items[i]);

                foreach (var prop in properties)
                {
                    var isHidden = Attribute.IsDefined(prop, typeof(TableListHiddenInput));
                    if (isHidden)
                    {
                        continue;
                    }

                    var propertyAttributesClone = CloneDictionary(propertyAttributes);
                    if (!allowModify && !propertyAttributesClone[prop.Name].ContainsKey("readonly"))
                    {
                        propertyAttributesClone[prop.Name].Add("readonly", "readonly");
                    }

                    var td = new TagBuilder("td");

                    var propType = GetPropertyType(prop);
                    if (propType == typeof(bool))
                    {
                        td.InnerHtml += html.CheckBox(fName + prop.Name, Convert.ToBoolean(prop.GetValue((TableListItem)items[i])), propertyAttributesClone[prop.Name]);
                    }
                    else
                    {
                        td.InnerHtml += html.TextBox(fName + prop.Name, prop.GetValue((TableListItem)items[i]), formattingAttributes[prop.Name]["DisplayFormatString"], propertyAttributesClone[prop.Name]);
                    }

                    td.InnerHtml += html.ValidationMessage(fName + prop.Name);

                    tr.InnerHtml += td;
                }

                var tdLast = new TagBuilder("td");

                foreach (var prop in properties)
                {
                    var isHidden = Attribute.IsDefined(prop, typeof(TableListHiddenInput));
                    if (!isHidden)
                    {
                        continue;
                    }

                    var val = prop.GetValue((TableListItem)items[i]);
                    tdLast.InnerHtml += html.Hidden(fName + prop.Name, val);

                    if (prop.Name == nameof(TableListItem.TL_AllowDelete) && (bool)val)
                    {
                        var a = new TagBuilder("a");
                        a.Attributes.Add("class", "table-list-mvc-item-delete");
                        a.Attributes.Add("href", "#");
                        //a.SetInnerText("Delete");

                        tdLast.InnerHtml += a;
                    }
                }

                tr.InnerHtml  += tdLast;
                tag.InnerHtml += tr;
            }
        }
Example #41
0
 public static MvcHtmlString CustomNumber(this HtmlHelper htmlHelper, string name, object htmlAttributes = null, object value = null, string format = null)
 {
     return(new MvcHtmlString(htmlHelper.TextBox(name, value, format, htmlAttributes).ToString().Replace("type=\"text\"", "type=\"number\"")));
 }
Example #42
0
        private static void AppendLastRow(HtmlHelper html, TagBuilder tag, List <PropertyInfo> properties, string fieldName, Dictionary <string, IDictionary <string, object> > propertyAttributes, Dictionary <string, IDictionary <string, string> > formattingAttributes, int index)
        {
            var fName = fieldName + "[" + index + "].";

            var tr = new TagBuilder("tr");

            tr.Attributes.Add("class", "table-list-mvc-item-new");
            tr.Attributes.Add("data-item-index", index.ToString());

            foreach (var prop in properties)
            {
                var isHidden = Attribute.IsDefined(prop, typeof(TableListHiddenInput));
                if (isHidden)
                {
                    continue;
                }

                //if (propertyAttributes[prop.Name].ContainsKey("readonly"))
                //{
                //    propertyAttributes[prop.Name].Remove("readonly");
                //}

                //TODO FIX
                propertyAttributes[prop.Name]["class"] += " table-list-mvc-ignore";

                var td = new TagBuilder("td");

                var propType = GetPropertyType(prop);
                if (propType == typeof(bool))
                {
                    td.InnerHtml += html.CheckBox(fName + prop.Name, false, propertyAttributes[prop.Name]);
                }
                else
                {
                    td.InnerHtml += html.TextBox(fName + prop.Name, null, formattingAttributes[prop.Name]["DisplayFormatString"], propertyAttributes[prop.Name]);
                }

                td.InnerHtml += html.ValidationMessage(fName + prop.Name);

                tr.InnerHtml += td;
            }

            var tdLast = new TagBuilder("td");

            foreach (var prop in properties)
            {
                var isHidden = Attribute.IsDefined(prop, typeof(TableListHiddenInput));
                if (!isHidden)
                {
                    continue;
                }

                if (prop.Name == nameof(TableListItem.TL_State))
                {
                    tdLast.InnerHtml += html.Hidden(fName + prop.Name, TableListItemState.Added);
                }
                else if (prop.Name == nameof(TableListItem.TL_AllowModify))
                {
                    tdLast.InnerHtml += html.Hidden(fName + prop.Name, true);
                }
                else if (prop.Name == nameof(TableListItem.TL_AllowDelete))
                {
                    tdLast.InnerHtml += html.Hidden(fName + prop.Name, true);

                    var a = new TagBuilder("a");
                    a.Attributes.Add("class", "table-list-mvc-item-delete");
                    a.Attributes.Add("href", "#");
                    //a.SetInnerText("Delete");

                    tdLast.InnerHtml += a;
                }
                else
                {
                    tdLast.InnerHtml += html.Hidden(fName + prop.Name);
                }
            }

            tr.InnerHtml  += tdLast;
            tag.InnerHtml += tr;
        }
 public void TestTextBox()
 {
     // TextBox
     Assert.AreEqual("<input id=\"account\" name=\"account\" value=\"admin\" type=\"text\" />",
                     HtmlHelper.TextBox("account", "admin"));
 }
 private static string HtmlInputTemplateHelper(HtmlHelper html, string inputType = null)
 {
     return html.TextBox(
             name: String.Empty,
             value: html.ViewContext.ViewData.TemplateInfo.FormattedModelValue,
             htmlAttributes: CreateHtmlAttributes(className: "text-box single-line", inputType: inputType))
         .ToHtmlString();
 }
Example #45
0
        public static string TextBoxWithValidation <TModel>(this HtmlHelper <TModel> htmlHelper, string validationKey, string name, object value, object htmlAttributes) where TModel : OxiteModel
        {
            OxiteModel model = htmlHelper.ViewData.Model;

            return(htmlHelper.TextBox(name, value, htmlAttributes) + htmlHelper.ValidationMessage(validationKey, model.Localize(validationKey)));
        }
 private static string HtmlInputTemplateHelper(HtmlHelper html, string inputType, object value)
 {
     return html.TextBox(
             name: String.Empty,
             value: value,
             htmlAttributes: CreateHtmlAttributes(html, className: "text-box single-line", inputType: inputType))
         .ToHtmlString();
 }
Example #47
0
        /// <summary>输出字符串</summary>
        /// <param name="Html"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <param name="length"></param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString ForString(this HtmlHelper Html, String name, String value, Int32 length = 0, Object htmlAttributes = null)
        {
            var atts = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            //if (!atts.ContainsKey("class")) atts.Add("class", "col-xs-10 col-sm-5");
            //if (!atts.ContainsKey("class")) atts.Add("class", "col-xs-12 col-sm-8 col-md-6 col-lg-4");
            if (!atts.ContainsKey("class"))
            {
                atts.Add("class", "form-control");
            }

            // 首先输出图标
            var ico = "";

            MvcHtmlString txt = null;

            if (name.EqualIgnoreCase("Pass", "Password"))
            {
                txt = Html.Password(name, (String)value, atts);
            }
            else if (name.EqualIgnoreCase("Phone"))
            {
                ico = "<span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-phone-alt\"></i></span>";
                if (!atts.ContainsKey("type"))
                {
                    atts.Add("type", "tel");
                }
                txt = Html.TextBox(name, value, atts);
            }
            else if (name.EqualIgnoreCase("MobilePhone", "CellularPhone"))
            {
                ico = "<span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-phone\"></i></span>";
                if (!atts.ContainsKey("type"))
                {
                    atts.Add("type", "tel");
                }
                txt = Html.TextBox(name, value, atts);
            }
            else if (name.EqualIgnoreCase("email", "mail"))
            {
                ico = "<span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-envelope\"></i></span>";
                if (!atts.ContainsKey("type"))
                {
                    atts.Add("type", "email");
                }
                txt = Html.TextBox(name, value, atts);
            }
            else if (name.EndsWithIgnoreCase("url"))
            {
                ico = "<span class=\"input-group-addon\"><i class=\"glyphicon glyphicon-home\"></i></span>";
                //if (!atts.ContainsKey("type")) atts.Add("type", "url");
                txt = Html.TextBox(name, value, atts);
            }
            else if (length < 0 || length > 300)
            {
                txt = Html.TextArea(name, value, 3, 20, atts);
            }
            else
            {
                txt = Html.TextBox(name, value, atts);
            }
            var icog = "<div class=\"input-group\">{0}</div>";
            var html = !String.IsNullOrWhiteSpace(ico) ? String.Format(icog, ico.ToString() + txt.ToString()) : txt.ToString();

            return(new MvcHtmlString(html));
        }
 public override MvcHtmlString WriteInput(HtmlHelper helper, object htmlAttributes)
 {
     IDictionary<string, object> efHtmlAttributes = new RouteValueDictionary(htmlAttributes);
     AddCommonHtmlAttributes(efHtmlAttributes);
     return helper.TextBox(this.InputName, this.Value, efHtmlAttributes);
 }