Example #1
0
        public void HiddenWithImplicitValueAndAttributesObject()
        {
            // Arrange
            var model = new ModelStateDictionary();

            model.SetModelValue("foo", "bar");
            HtmlHelper helper = HtmlHelperFactory.Create(model);

            // Act
            var html = helper.Hidden("foo", null, new { attr = "attr-val" });

            // Assert
            Assert.Equal(@"<input attr=""attr-val"" id=""foo"" name=""foo"" type=""hidden"" value=""bar"" />", html.ToHtmlString());
        }
    public static MvcHtmlString HiddenForEnumerable <TModel, TProperty>(this HtmlHelper <TModel> helper,
                                                                        Expression <Func <TModel, IEnumerable <TProperty> > > expression)
    {
        var sb         = new StringBuilder();
        var membername = expression.GetMemberName();
        var model      = helper.ViewData.Model;
        var list       = expression.Compile()(model);

        for (var i = 0; i < list.Count(); i++)
        {
            sb.Append(helper.Hidden(string.Format("{0}[{1}]", membername, i), list.ElementAt(i)));
        }
        return(new MvcHtmlString(sb.ToString()));
    }
Example #3
0
        public static HtmlString CheckBoxList <T, TModel, TValue, TText>(this HtmlHelper <TModel> helper,
                                                                         string listName, string valueProperty,
                                                                         string textProperty,
                                                                         Dictionary <T, bool> checkedList,
                                                                         Func <T, TValue> value,
                                                                         Func <T, TText> text)
        {
            var builder = new StringBuilder();

            for (int i = 0; i < checkedList.Count; i++)
            {
                T item = checkedList.Keys.ToList()[i];
                builder.AppendLine("<p>");
                builder.AppendLine(
                    helper.Hidden(listName + "[" + i + "].Key." + valueProperty, value(item)).ToHtmlString());
                builder.AppendLine(
                    helper.Hidden(listName + "[" + i + "].Key." + textProperty, text(item)).ToHtmlString());
                builder.AppendLine(helper.CheckBox(listName + "[" + i + "].Value", checkedList[item]).ToHtmlString());
                builder.AppendLine(text(item).ToString());
                builder.AppendLine("</p>");
            }
            return(new HtmlString(builder.ToString()));
        }
Example #4
0
        public void HiddenWithExplicitValue()
        {
            // Arrange
            HtmlHelper helper = HtmlHelperFactory.Create();

            // Act
            var html = helper.Hidden("foo", "DefaultFoo");

            // Assert
            Assert.Equal(
                @"<input id=""foo"" name=""foo"" type=""hidden"" value=""DefaultFoo"" />",
                html.ToHtmlString()
                );
        }
Example #5
0
        public override string ToHtmlString()
        {
            return($@"
		{_label}
		<div class=""input-group"">
			<span class=""input-group-addon"">
				<i class=""fa fa-search""></i>
			</span>
			{_helper.TextBox(_textBoxId, null, new { @class = "form-control", id = _textBoxId, autocomplete = "off" })}
			{MensajeValidacionHtml(_helper, _expression)}
		</div>
		{_helper.Hidden(_expressionId, "")}
		{ScriptString()}"        );
        }
Example #6
0
        public void HiddenWithExplicitOverwritesAttributeValue()
        {
            // Arrange
            HtmlHelper helper = HtmlHelperFactory.Create();

            // Act
            var html = helper.Hidden("foo", "fooValue", new { value = "barValue" });

            // Assert
            Assert.Equal(
                @"<input id=""foo"" name=""foo"" type=""hidden"" value=""fooValue"" />",
                html.ToHtmlString()
                );
        }
Example #7
0
        public void HiddenWithBinaryArrayValueRendersBase64EncodedValue()
        {
            // Arrange
            HtmlHelper helper = HtmlHelperFactory.Create();

            // Act
            var result = helper.Hidden("ProductName", new Binary(new byte[] { 23, 43, 53 }));

            // Assert
            Assert.Equal(
                "<input id=\"ProductName\" name=\"ProductName\" type=\"hidden\" value=\"Fys1\" />",
                result.ToHtmlString()
                );
        }
        public static MvcHtmlString QueryAsHiddenFields(this HtmlHelper htmlHelper)
        {
            var result = new StringBuilder();
            var query  = htmlHelper.ViewContext.HttpContext.Request.QueryString;

            foreach (string key in query.Keys)
            {
                if ((key != "DistanceDD.SelectedDistanceLimit") && (key != "ChangeLocation") && (key != "Search.PickUpDateSearch") && (key != "Search.FreeSearch"))
                {
                    result.Append(htmlHelper.Hidden(key, query[key]).ToHtmlString());
                }
            }
            return(MvcHtmlString.Create(result.ToString()));
        }
Example #9
0
        public void HiddenWithModelValue()
        {
            // Arrange
            var model = new ModelStateDictionary();

            model.SetModelValue("foo", "bar");
            HtmlHelper helper = HtmlHelperFactory.Create(model);

            // Act
            var html = helper.Hidden("foo");

            // Assert
            Assert.Equal(@"<input id=""foo"" name=""foo"" type=""hidden"" value=""bar"" />", html.ToHtmlString());
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="textareaId">编辑框的id</param>
        /// <param name="seletorId">出发按钮的id</param>
        /// <returns></returns>
        public static MvcHtmlString AtUser(this HtmlHelper htmlHelper, string controlNamePrefix)
        {
            if (UserContext.CurrentUser == null)
            {
                return(MvcHtmlString.Empty);
            }
            htmlHelper.Script("~/Bundle/Scripts/AtUser");
            int    randomNum = new Random().Next(100000, 999999);
            string url       = CachedUrlHelper.Action("_AtRemindUserForAt", "Channel", "Common");

            return(htmlHelper.Hidden("AtUser_" + randomNum, controlNamePrefix, new RouteValueDictionary {
                { "data-url", url }
            }));
        }
Example #11
0
        public void HiddenWithModelValueOverwritesAttributeValue()
        {
            // Arrange
            var model = new ModelStateDictionary();

            model.SetModelValue("foo", "fooValue");
            HtmlHelper helper = new HtmlHelper(model);

            // Act
            var html = helper.Hidden("foo", null, new { value = "barValue" });

            // Assert
            Assert.AreEqual(@"<input id=""foo"" name=""foo"" type=""hidden"" value=""fooValue"" />", html.ToHtmlString());
        }
Example #12
0
        public void HiddenWithExplicitValueAndAttributesDictionary()
        {
            // Arrange
            HtmlHelper helper = HtmlHelperFactory.Create();

            // Act
            var html = helper.Hidden("foo", "DefaultFoo", new Dictionary <string, object> {
                { "attr", "attr-val" }
            });

            // Assert
            Assert.Equal(@"<input attr=""attr-val"" id=""foo"" name=""foo"" type=""hidden"" value=""DefaultFoo"" />",
                         html.ToHtmlString());
        }
Example #13
0
        public static string Captcha(this HtmlHelper html, string name)
        {
            // Pick a GUID to represent this challenge
            string challengeGuid = Guid.NewGuid().ToString();
            // Generate and store a random solution text
            var session = html.ViewContext.HttpContext.Session;

            session[SessionKeyPrefix + challengeGuid] = MakeRandomSolution();
            // Render an <IMG> tag for the distorted text,
            // plus a hidden field to contain the challenge GUID
            var    urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            string url       = urlHelper.Action("Render", "CaptchaImage", new { challengeGuid });

            return(string.Format(ImgFormat, url) + html.Hidden(name, challengeGuid));
        }
Example #14
0
        /// <summary>
        ///  Generates captcha image with unique value and guid to validate requests.
        /// </summary>
        public static MvcHtmlString Captcha(this HtmlHelper html, string name)
        {
            string challengeGuid = Guid.NewGuid().ToString();

            // Generate and save unique text for captcha.
            var session = html.ViewContext.HttpContext.Session;

            session[SESSION_KEY_PREFIX + challengeGuid] = _MakeRandomSolution();

            // Generate page with captcha image and hidder field containing unique Guid of the captcha.
            var    urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            string url       = urlHelper.Action("Render", "CaptchaImage", new { challengeGuid });

            return(MvcHtmlString.Create(string.Format(IMAGE_FORMAT, url) + html.Hidden(name, challengeGuid)));
        }
Example #15
0
        MvcHtmlString ICustomFieldRender <HiddenSingleLineFieldType> .RenderHtmlEditor <TModel>(HtmlHelper <TModel> html, IField field, IDictionary <string, object> htmlAttributes, params object[] additionalParameters)
        {
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }
            if (!string.IsNullOrEmpty(field.alias))
            {
                htmlAttributes["class"] = (htmlAttributes.GetValueOrDefault("class", null) ?? "") + " FieldAlias_" + field.alias;
            }

            var value = (field as FieldData)?.ToString();

            return(html.Hidden($"fieldValue_{field.IdField}", value, htmlAttributes));
        }
Example #16
0
        /// <summary>
        /// 指定された <see cref="ModelMetadata"/> の HTML input(file) 要素を返します。
        /// </summary>
        /// <param name="html">このメソッドによって拡張される HTML ヘルパー インスタンス</param>
        /// <param name="metadata">この要素を表すメタデータ</param>
        /// <param name="extension">許可するファイルの拡張子</param>
        /// <returns>HTML input 要素</returns>
        private static MvcHtmlString FileHelper(HtmlHelper html, ModelMetadata metadata, string extension)
        {
            var result   = new StringBuilder();
            var name     = metadata.PropertyName;
            var fullName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);

            // FILE要素の生成
            var fileFullName = fullName + "-File";
            var file         = new TagBuilder("input");

            file.MergeAttribute("type", "file");
            file.MergeAttribute("name", fileFullName, true);
            file.MergeAttribute("accept", extension);
            file.MergeAttribute("data-item-id", fullName);
            file.MergeAttribute("data-file-extension", extension);
            file.GenerateId(fileFullName);
            result.Append(file.ToString(TagRenderMode.SelfClosing));

            // HIDDEN要素の生成
            result.Append(html.Hidden(fullName).ToString());
            result.Append(html.Hidden(fullName + "Original").ToString());

            return(MvcHtmlString.Create(result.ToString()));
        }
        public void HiddenWithByteArrayValueRendersBase64EncodedValue()
        {
            // Arrange
            Mock <ViewContext>        mockViewContext        = new Mock <ViewContext>();
            Mock <IViewDataContainer> mockIViewDataContainer = new Mock <IViewDataContainer>();
            ViewDataDictionary        viewData = new ViewDataDictionary();

            mockIViewDataContainer.Expect(c => c.ViewData).Returns(viewData);
            HtmlHelper htmlHelper = new HtmlHelper(mockViewContext.Object, mockIViewDataContainer.Object);

            // Act
            string result = htmlHelper.Hidden("ProductName", ByteArrayModelBinderTest.Base64TestBytes);

            // Assert
            Assert.AreEqual("<input id=\"ProductName\" name=\"ProductName\" type=\"hidden\" value=\"Fys1\" />", result);
        }
Example #18
0
        public void HiddenWithModelValueAndAttributesDictionary()
        {
            // Arrange
            var model = new ModelStateDictionary();

            model.SetModelValue("foo", "bar");
            HtmlHelper helper = new HtmlHelper(model);

            // Act
            var html = helper.Hidden("foo", null, new Dictionary <string, object> {
                { "attr", "attr-val" }
            });

            // Assert
            Assert.AreEqual(@"<input attr=""attr-val"" id=""foo"" name=""foo"" type=""hidden"" value=""bar"" />", html.ToHtmlString());
        }
Example #19
0
        public static MvcHtmlString LookupHtml <TModel>(this HtmlHelper <TModel> html, string idFieldName, string textFieldName, string actionName, string controllerName, string jsonActionName, string jsonControllerName) where TModel : class
        {
            ViewDataDictionary <TModel> ViewData = html.ViewData;

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

            foreach (ModelMetadata m in ViewData.ModelMetadata.Properties)
            {
                sbFields.Append(html.Hidden(m.PropertyName, typeof(TModel).GetProperty(m.PropertyName).GetValue(ViewData.Model, null), new { @id = string.Format("HiddenID_{0}{1}", ViewData.ModelMetadata.PropertyName, m.PropertyName) }).ToHtmlString());
            }
            sbFields.Append(string.Format("<span id=\"LabelID_{0}\">{1}</span>", ViewData.ModelMetadata.PropertyName, typeof(TModel).GetProperty(textFieldName).GetValue(ViewData.Model, null) ?? "[Display Text]"));
            sbFields.Append(string.Format("<input type=\"button\" value=\"...\" class=\"t-button\" onclick=\"lookupOpenWindow('#SearchWindow_{0}')\" />", ViewData.ModelMetadata.PropertyName));

            sbFields.Append(
                html.Telerik().Window().BuildWindow("SearchWindow_" + ViewData.ModelMetadata.PropertyName)
                .Modal(true)
                .Content(
                    html.Telerik().Grid <TModel>()
                    .Name("SearchWindowGrid_" + ViewData.ModelMetadata.PropertyName)
                    .Selectable()
                    .Columns(columns => {
                foreach (ModelMetadata m in ViewData.ModelMetadata.Properties)
                {
                    if (m.ShowForDisplay)
                    {
                        columns.Bound(m.PropertyName);
                    }
                }
                columns.Bound(idFieldName)
                .ClientTemplate("<a href='#' onClick='onMasterSelect(<#= " + idFieldName + " #>, \"#HiddenID_" + ViewData.ModelMetadata.PropertyName + "\", \"#LabelID_" + ViewData.ModelMetadata.PropertyName + "\", \"" + urlHelper.Action(jsonActionName, jsonControllerName) + "\", \"#SearchWindow_" + ViewData.ModelMetadata.PropertyName + "\")'>Select</a>").Title("Select");
            })
                    .EnableCustomBinding(true)
                    .Pageable(paging => paging.PageSize(ConfigurationHelper.GetsmARTLookupGridPageSize())
                              .Style(Telerik.Web.Mvc.UI.GridPagerStyles.NextPreviousAndNumeric)
                              .Total(100))
                    .DataKeys(keys => keys.Add(idFieldName))
                    .DataBinding(binding => binding.Ajax().Select(actionName, controllerName))
                    .ClientEvents(events => events.OnLoad("SetDefaultFilterToContains")).ToHtmlString()
                    )
                .Visible(false).ToHtmlString()
                );

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

            return(htmlString);
        }
Example #20
0
        public static MvcHtmlString ConcurrencyCheck(
            this HtmlHelper htmlHelper,
            object concurrencyCheckValue)
        {
            if (concurrencyCheckValue == null)
            {
                return(MvcHtmlString.Empty);
            }

            if (concurrencyCheckValue is DateTime)
            {
                concurrencyCheckValue = (concurrencyCheckValue as DateTime?).Value
                                        .ToString("dd/MM/yyyy HH:mm:ss.fff", CultureInfo.CurrentCulture);
            }

            return(htmlHelper.Hidden("__ConcurrencyCheck", concurrencyCheckValue));
        }
Example #21
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 #22
0
        public static MvcHtmlString Hidden(this AjaxHelper ajaxHelper,
                                           string name,
                                           object value    = null,
                                           string cssClass = null,
                                           string id       = null,
                                           string style    = null,
                                           string dataBind = null)
        {
            HtmlHelper htmlHelper = ajaxHelper.GetHtmlHelper();

            if (dataBind == null)
            {
                dataBind = "value: " + name;
            }

            return(htmlHelper.Hidden(name, value, Attributes(cssClass, id, style, dataBind)));
        }
Example #23
0
        protected string Form_Delete_Body <TModel>(AjaxHelper <TModel> helper)
        {
            var htmlHelper  = new HtmlHelper <TModel>(helper.ViewContext, helper.ViewDataContainer);
            var model       = helper.ViewData.Model;
            var modelIdName = ModelHelper <TModel> .GetPrimaryKeys()[0].Name;

            var modelIdValue = ModelHelper <TModel> .GetPrimaryKeyValues(model)[0];

            var row1 = htmlHelper.Hidden(modelIdName, modelIdValue);
            var row2 = new DivControl(model.ToString());
            var row3 = htmlHelper.Button()
                       .SetText(ConstViews.INFO_Delete)
                       .IsSubmitBtn(true)
                       .MergeAttribute("onclick", "hideElement('" + modelIdValue + "')");

            return(string.Concat(row1, row2, row3));
        }
Example #24
0
        public static string DropDownList(this HtmlHelper htmlHelper, string name, SelectList selectList, object htmlAttributes, bool isEnabled)
        {
            RouteValueDictionary htmlAttributeDictionary = new RouteValueDictionary(htmlAttributes);

            if (!isEnabled)
            {
                htmlAttributeDictionary["disabled"] = "disabled";

                StringBuilder inputItemBuilder = new StringBuilder();
                inputItemBuilder.AppendLine(htmlHelper.DropDownList(string.Format("{0}_view", name), selectList,
                                                                    htmlAttributeDictionary));
                inputItemBuilder.AppendLine(htmlHelper.Hidden(name, selectList.SelectedValue));
                return(inputItemBuilder.ToString());
            }

            return(htmlHelper.DropDownList(name, selectList, htmlAttributeDictionary));
        }
Example #25
0
        public static MvcHtmlString GenerateHiddenFields <TModel>(this HtmlHelper <TModel> Html, IMnBaseElement model)
        {
            var result = string.Empty;

            result += Html.Hidden("Name", model.Name).ToHtmlString();
            result += Html.Hidden("Title", model.Title).ToHtmlString();
            result += Html.Hidden("HelpText", model.HelpText).ToHtmlString();
            result += Html.Hidden("ElementId", model.ElementId).ToHtmlString();
            result += Html.Hidden("CurrentMode", model.CurrentMode).ToHtmlString();
            result += Html.Hidden("VisibleMode", model.VisibleMode).ToHtmlString();
            result += Html.Hidden("ModelType", model.GetType()).ToHtmlString();

            result = model.AccessRole.Aggregate(result, (current, accRole) => current + Html.HiddenFor(modelItem => accRole).ToHtmlString());

            return(MvcHtmlString.Create(result));
        }
Example #26
0
        public static MvcHtmlString ValidationResultsFor <TValidatable>(this HtmlHelper <TValidatable> htmlHelper, TValidatable model)
            where TValidatable : IValidatable
        {
            var properties =
                from property in model.GetType().GetProperties()
                where Attribute.IsDefined(property, typeof(RequiredForValidationAttribute))
                select property;

            return(BuildHtmlMarkupWithStringBuilder(builder =>
            {
                foreach (var property in properties)
                {
                    builder.Append(htmlHelper.Hidden(property.Name, property.GetValue(model)));
                }

                builder.Append(htmlHelper.Partial(Partials.Validation, model));
            }));
        }
Example #27
0
        public static MvcHtmlString EncryptedHidden(this HtmlHelper helper, string name, object value)
        {
            if (value == null)
            {
                value = string.Empty;
            }
            var strValue = value.ToString();
            IEncryptSettingsProvider settings = new EncryptSettingsProvider();
            var encrypter      = new RijndaelStringEncrypter(settings, helper.GetActionKey());
            var encryptedValue = encrypter.Encrypt(strValue);

            encrypter.Dispose();

            var encodedValue = helper.Encode(encryptedValue);
            var newName      = string.Concat(settings.EncryptionPrefix, name);

            return(helper.Hidden(newName, encodedValue));
        }
Example #28
0
        public static string TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes, bool isEnabled)
        {
            RouteValueDictionary htmlAttributeDictionary = new RouteValueDictionary(htmlAttributes);

            if (!isEnabled)
            {
                htmlAttributeDictionary["disabled"] = "disabled";

                StringBuilder inputItemBuilder = new StringBuilder();

                inputItemBuilder.Append(htmlHelper.TextBox(string.Format("{0}_view", name), value, htmlAttributeDictionary));
                inputItemBuilder.Append(htmlHelper.Hidden(name, value));

                return(inputItemBuilder.ToString());
            }

            return(htmlHelper.TextBox(name, value, htmlAttributeDictionary));
        }
        public static string TextBoxWithValidation <TModel>(this HtmlHelper <TModel> htmlHelper, string validationKey, string name, object value, object htmlAttributes, bool isEnabled) where TModel : OxiteViewModel
        {
            RouteValueDictionary htmlAttributeDictionary = new RouteValueDictionary(htmlAttributes);

            if (!isEnabled)
            {
                htmlAttributeDictionary["disabled"] = "disabled";

                StringBuilder inputItemBuilder = new StringBuilder();

                inputItemBuilder.Append(TextBoxWithValidation(htmlHelper, validationKey, string.Format("{0}_view", name), value, htmlAttributeDictionary));
                inputItemBuilder.Append(htmlHelper.Hidden(name, value));

                return(inputItemBuilder.ToString());
            }

            return(htmlHelper.TextBoxWithValidation(validationKey, name, value, htmlAttributes));
        }
Example #30
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))));
        }
        public static MvcHtmlString HiddenCollectionOf <TModel, TProperty>(this HtmlHelper htmlHelper, TModel model,
                                                                           Expression <Func <TModel, IEnumerable <TProperty> > > collectionExpression)
        {
            var collection = collectionExpression.Compile().Invoke(model);
            var enumerable = collection as IList <TProperty> ?? collection.ToList();

            if (!enumerable.Any())
            {
                return(null);
            }

            var collectionPropertyName = ((MemberExpression)collectionExpression.Body).Member.Name;

            var memberExpression = ((MemberExpression)collectionExpression.Body).Expression.ToString();

            if (NestedCollection(memberExpression))
            {
                collectionPropertyName = CollectionPropertyName(collectionPropertyName, memberExpression);
            }

            var properties = TypeDescriptor.GetProperties(typeof(TProperty));

            var hiddenHtmlCollection = new List <string>();
            var index = 0;

            foreach (var item in enumerable)
            {
                foreach (var property in properties)
                {
                    var propertyValue = ((PropertyDescriptor)property).GetValue(item);
                    var propertyName  = ((PropertyDescriptor)property).Name;

                    hiddenHtmlCollection.Add(htmlHelper.Hidden(
                                                 FormatCollectionName(collectionPropertyName, index, propertyName),
                                                 propertyValue,
                                                 new { id = FormatCollectionName(collectionPropertyName, index, propertyName) })
                                             .ToHtmlString());
                }

                index++;
            }

            return(MvcHtmlString.Create(hiddenHtmlCollection.Aggregate((current, next) => current + next)));
        }
Example #32
0
 private static void KeepQueryStringAlive(StringBuilder builder,
     HtmlHelper html, PagingOptions option)
 {
     var queryString = html.ViewContext.HttpContext.Request.QueryString;
     foreach (string key in queryString.AllKeys)
     {
         if (!string.Equals(key, option.PageSegmentName, StringComparison.CurrentCultureIgnoreCase))
             builder.Append(html.Hidden(key, queryString[key], new { id = (string)null }));
     }
 }
Example #33
0
 public static MvcHtmlString WriteIndex(HtmlHelper helper, EntityListBase listBase, TypeContext itemTC, int itemIndex)
 {
     return helper.Hidden(itemTC.Compose(EntityListBaseKeys.Indexes), "{0};{1}".Formato(
         listBase.ShouldWriteOldIndex(itemTC) ? itemIndex.ToString() : "",
         itemIndex.ToString()));
 }
        internal static string HiddenInputTemplate(HtmlHelper html)
        {
            string result;
            ViewDataDictionary viewData = html.ViewContext.ViewData;
            if (viewData.ModelMetadata.HideSurroundingHtml)
            {
                result = String.Empty;
            }
            else
            {
                result = DefaultDisplayTemplates.StringTemplate(html);
            }

            object model = viewData.Model;

            Binary modelAsBinary = model as Binary;
            if (modelAsBinary != null)
            {
                model = Convert.ToBase64String(modelAsBinary.ToArray());
            }
            else
            {
                byte[] modelAsByteArray = model as byte[];
                if (modelAsByteArray != null)
                {
                    model = Convert.ToBase64String(modelAsByteArray);
                }
            }

            object htmlAttributesObject = viewData[HtmlAttributeKey];
            IDictionary<string, object> htmlAttributesDict = htmlAttributesObject as IDictionary<string, object>;

            MvcHtmlString hiddenResult;

            if (htmlAttributesDict != null) 
            {
                hiddenResult = html.Hidden(String.Empty, model, htmlAttributesDict);
            } 
            else 
            {
                hiddenResult = html.Hidden(String.Empty, model, htmlAttributesObject);
            }

            result += hiddenResult.ToHtmlString();

            return result;
        }
        internal static string HiddenInputTemplate(HtmlHelper html)
        {
            string result;

            if (html.ViewContext.ViewData.ModelMetadata.HideSurroundingHtml)
            {
                result = String.Empty;
            }
            else
            {
                result = DefaultDisplayTemplates.StringTemplate(html);
            }

            object model = html.ViewContext.ViewData.Model;

            Binary modelAsBinary = model as Binary;
            if (modelAsBinary != null)
            {
                model = Convert.ToBase64String(modelAsBinary.ToArray());
            }
            else
            {
                byte[] modelAsByteArray = model as byte[];
                if (modelAsByteArray != null)
                {
                    model = Convert.ToBase64String(modelAsByteArray);
                }
            }

            result += html.Hidden(String.Empty, model).ToHtmlString();
            return result;
        }
 public override MvcHtmlString Generate(HtmlHelper htmlHelper, string name, object value)
 {
     return htmlHelper.Hidden(name, value, new { @class = CssClass, style = CssStyle });
 }
        public static string RenderReadOnly(HtmlHelper html, BootstrapReadOnlyModel model, bool isPassword)
        {
            var combinedHtml = "{0}{1}{2}";

            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));

            if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.Add("id", model.id);
            if (model.tooltipConfiguration != null) model.htmlAttributes.MergeHtmlAttributes(model.tooltipConfiguration.ToDictionary());
            if (model.tooltip != null) model.htmlAttributes.MergeHtmlAttributes(model.tooltip.ToDictionary());
            // assign placeholder class
            if (!string.IsNullOrEmpty(model.placeholder)) model.htmlAttributes.Add("placeholder", model.placeholder);
            // build html for input

            string input = html.Hidden(model.htmlFieldName, model.value).ToHtmlString();

            if (model.value != null && model.value.GetType().IsEnum)
            {
                input =  input + ((Enum)model.value).GetEnumDescription();
            }
            else
            {
                input = input + html.Encode(model.value);

            }

            // 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))
            {
                var appendPrependContainer = new TagBuilder("div");
                var addOnPrependString = "";
                var addOnAppendString = "";
                var addOnPrependButtons = "";
                var addOnAppendButtons = "";
                var addOnPrependIcon = "";
                var addOnAppendIcon = "";

                var 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}";
            }

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

            return MvcHtmlString.Create(string.Format(combinedHtml, input, helpText, validationMessage)).ToString();
        }
Example #38
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)));
 }