Example #1
0
        public static MvcHtmlString RenderDetails <TModel>(this HtmlHelper html,
                                                           TModel item,
                                                           string fieldSize = "input-xxlarge") where TModel : class
        {
            var url = new UrlHelper(html.ViewContext.RequestContext);
            var propertiesToDisplay = GetDisplayProperties <TModel>();
            var sb = new StringBuilder();

            sb.AppendLine("<form class=\"form-horizontal\">");
            sb.AppendLine("<fieldset>");
            sb.AppendLine("<legend>Details</legend>");

            foreach (var property in propertiesToDisplay)
            {
                sb.AppendLine("<div class=\"control-group\">");
                sb.AppendFormat("<label class=\"control-label\" for=\"input{0}\">{0}</label>", property.Name);
                sb.AppendLine("<div class=\"controls\">");
                sb.AppendFormat("<input type=\"text\" id=\"input{0}\" value=\"{1}\" class=\"{2} uneditable-input\"/>",
                                property.Name,
                                html.AttributeEncode(property.GetValue(item, null)),
                                fieldSize);
                sb.AppendLine("</div>");
                sb.AppendLine("</div>");
            }

            sb.AppendLine("</fieldset>");
            sb.AppendLine("</form>");

            return(MvcHtmlString.Create(sb.ToString()));
        }
Example #2
0
        public static MvcHtmlString EditorForMany <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, IEnumerable <TValue> > > propertyExpression, Expression <Func <TValue, string> > indexResolverExpression = null, bool includeIndexField = true)
            where TModel : class
        {
            IEnumerable <TValue> tValues       = propertyExpression.Compile()(html.ViewData.Model);
            StringBuilder        stringBuilder = new StringBuilder();
            string expressionText    = ExpressionHelper.GetExpressionText(propertyExpression);
            string fullHtmlFieldName = html.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);
            Func <TValue, string> func;

            func = indexResolverExpression?.Compile() ?? (x => null);
            foreach (TValue tValue in tValues)
            {
                stringBuilder.Append("<div class=\"item-render\">");
                var    variable = new { Item = tValue };
                string str      = func(tValue);
                Expression <Func <TModel, TValue> > expression = Expression.Lambda <Func <TModel, TValue> >(Expression.MakeMemberAccess(Expression.Constant(variable), variable.GetType().GetProperty("Item")), propertyExpression.Parameters);
                str = (!string.IsNullOrEmpty(str) ? html.AttributeEncode(str) : Guid.NewGuid().ToString());
                if (includeIndexField)
                {
                    stringBuilder.Append(_EditorForManyIndexField(fullHtmlFieldName, str, indexResolverExpression));
                }
                stringBuilder.Append(html.EditorFor(expression, null, $"{expressionText}[{str}]"));
                stringBuilder.Append("</div>");
            }
            return(new MvcHtmlString(stringBuilder.ToString()));
        }
Example #3
0
 internal static string UrlTemplate(HtmlHelper html)
 {
     return(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "<a href=\"{0}\">{1}</a>", new object[2]
     {
         (object)html.AttributeEncode(html.ViewContext.ViewData.Model),
         (object)html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue)
     }));
 }
Example #4
0
        /// <summary>
        /// Returns true if the specified model property has validation errors
        /// </summary>
        internal static bool HasModelStateErros <TModel, TProperty>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TProperty> > expression)
        {
            var propertyName = ExpressionHelper.GetExpressionText(expression);
            var name         = helper.AttributeEncode(helper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName));

            return(helper.ViewData.ModelState[name] != null &&
                   helper.ViewData.ModelState[name].Errors != null &&
                   helper.ViewData.ModelState[name].Errors.Count > 0);
        }
Example #5
0
        private static string GetSubMenuItem(HtmlHelper html, UrlHelper url, string linkText, string actionName, string controllerName)
        {
            string currentAction = html.ViewContext.RouteData.GetRequiredString("action");

            return(string.Format("<li{2}><a href=\"{0}\">{1}</a></li>",
                                 html.AttributeEncode(url.Action(actionName, controllerName)),
                                 linkText,
                                 actionName == currentAction ? " class=\"active\"" : string.Empty));
        }
Example #6
0
        public static MvcHtmlString GetImageLink(this HtmlHelper html, ImageModel image, bool useThumbnail, object imageAttributes = null, object anchorAttributes = null)
        {
            if (image == null || image.Url.IsNullOrWhiteSpace())
            {
                return(MvcHtmlString.Create(String.Format("<img class=\"avatar\" src=\"{0}\" />", System.Web.VirtualPathUtility.ToAbsolute("~/content/images/no-image.gif"))));
            }

            var thumbConfig = useThumbnail ? "ThumbPath" : "MediumImagePath";

            var config    = ObjectFactory.GetInstance <IConfig>();
            var imagePath = VirtualPathUtility.Combine(VirtualPathUtility.ToAbsolute(config.GetSetting <string>("LargeImagePath")), image.Url);
            var thumbPath = VirtualPathUtility.Combine(VirtualPathUtility.ToAbsolute(config.GetSetting <string>(thumbConfig)), image.Url);

            var anchorTag = new TagBuilder("a");
            var imageTag  = new TagBuilder("img");

            if (anchorAttributes != null)
            {
                GetAnonTypeValues(anchorAttributes).ForEach(a =>
                {
                    anchorTag.Attributes.Add(a);
                });
            }

            if (imageAttributes != null)
            {
                GetAnonTypeValues(imageAttributes).ForEach(a =>
                {
                    imageTag.Attributes.Add(a);
                });
            }

            anchorTag.Attributes["href"] = html.AttributeEncode(imagePath);
            imageTag.Attributes["src"]   = html.AttributeEncode(thumbPath);
            imageTag.Attributes["alt"]   = image.Caption;

            anchorTag.InnerHtml = imageTag.ToString();

            return(MvcHtmlString.Create(anchorTag.ToString()));

            //var tag = String.Format("<a href=\"{0}\"><img src=\"{1}\" /></a>", html.AttributeEncode(imagePath), html.AttributeEncode(thumbPath));

            //return MvcHtmlString.Create(tag);
        }
Example #7
0
        /// <summary>
        /// Renders dictionary to attributes
        /// </summary>
        public static IHtmlString RenderAttrs(this HtmlHelper self, Dictionary <string, string> attrs)
        {
            string s = string.Empty;

            foreach (var kv in attrs)
            {
                s += s + @" " + kv.Key + @"=""" + self.AttributeEncode(kv.Value) + @"""";
            }
            return(self.Raw(s));
        }
Example #8
0
        public static MvcHtmlString EventImage(this HtmlHelper html, EventImage image, int?size)
        {
            var url = new UrlHelper(html.ViewContext.RequestContext);

            var imgUrl = url.EventImage(image, size);

            return(new MvcHtmlString(string.Format(
                                         "<img src=\"{0}\" />",
                                         html.AttributeEncode(imgUrl))));
        }
Example #9
0
        public void AttributeEncodeStringNull()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();

            // Act
            string encodedHtml = htmlHelper.AttributeEncode((string)null);

            // Assert
            Assert.AreEqual("", encodedHtml);
        }
Example #10
0
        public void AttributeEncodeString()
        {
            // Arrange
            HtmlHelper htmlHelper = MvcHelper.GetHtmlHelper();

            // Act
            string encodedHtml = htmlHelper.AttributeEncode(@"<"">");

            // Assert
            Assert.AreEqual(encodedHtml, "&lt;&quot;>", "Text is not being properly HTML attribute-encoded.");
        }
Example #11
0
        public void AttributeEncodeObjectNull()
        {
            // Arrange
            HtmlHelper htmlHelper = GetHtmlHelper();

            // Act
            string encodedHtml = htmlHelper.AttributeEncode((object)null);

            // Assert
            Assert.AreEqual("", encodedHtml);
        }
        /// <summary>
        /// Avoids using the HtmlFieldPrefix when getting the NameFor an expression.
        /// Also, grabs only the furthest descended property (x => x.Address.City will return City).
        /// </summary>
        private static MvcHtmlString NameFor <TModel, TProperty>(this HtmlHelper <TModel> html, Expression <Func <TModel, TProperty> > expression)
        {
            var name = ExpressionHelper.GetExpressionText(expression);

            if (!string.IsNullOrWhiteSpace(name))
            {
                var nameSplit = name.Split('.');
                name = nameSplit[nameSplit.Length - 1];
            }
            return(MvcHtmlString.Create(html.AttributeEncode(name)));
        }
Example #13
0
        public static IHtmlString ButtonDropdowns(this HtmlHelper html, string actionName, IList <TbMenuItem> menuItems, object htmlAttributes = null)
        {
            var attributes = htmlAttributes as IDictionary <string, object> ??
                             HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            var dropdown = new StringBuilder();

            var btnStyle = "btn btn-" + attributes.GetString("theme", "default");

            attributes.Remove("theme");

            // overwrite style
            var @class = attributes.ContainsKey("class") ? html.AttributeEncode(attributes["class"]) : string.Empty;

            if (!string.IsNullOrWhiteSpace(@class))
            {
                btnStyle += " " + @class;
            }

            var nItems    = menuItems.Count(t => t != null && t.Visible);
            var downgrade = attributes.Get <bool>("downgrade", false);

            attributes.Remove("downgrade");

            if (nItems == 1 && downgrade)
            {
                var item = menuItems.First(t => t != null && t.Visible);

                var route = HtmlHelper.AnonymousObjectToHtmlAttributes(item.RouteValues);
                var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(item.Attributes);
                attrs.Ensure("class", btnStyle);

                var link = html.RouteLink(item.Text, item.RouteName, route, attrs);

                dropdown.Append(link);
            }
            else
            {
                dropdown.Append("<div class=\"btn-group\">");

                BuildCaption(html, actionName, attributes, dropdown, btnStyle);

                // create menu item
                var items = menuItems.Where(t => t == null || t.Visible).ToList();
                BuildMenuItem(html, items, dropdown);

                dropdown.Append("</div>");
            }

            // create btn-group
            return(new MvcHtmlString(dropdown.ToString()));
        }
        /// <summary>
        /// Renders the Settings &amp; Styles associated with the <paramref name="contentItem"/>.
        /// </summary>
        /// <typeparam name="TContentItem">The type used for the content item</typeparam>
        /// <param name="helper">The <see cref="HtmlHelper"/> instance.</param>
        /// <param name="contentItem">The item which holds the configuration for Settings & Styles. This is typically an area or row in the Umbraco Grid.</param>
        /// <param name="attributesService">An <see cref="IGridSettingsAttributesService" /> which handles the resolution of attributes.</param>
        /// <returns>A <see cref="MvcHtmlString" /> containing all the resolved attributes with their values.</returns>
        public static MvcHtmlString RenderGridSettingAttributes <TContentItem>(this HtmlHelper helper, TContentItem contentItem, IGridSettingsAttributesService <TContentItem> attributesService)
        {
            var attributes = attributesService.GetAllAttributes(contentItem);

            var output = new StringBuilder();

            foreach (var attribute in attributes)
            {
                output.AppendFormat(" {0}=\"{1}\"", attribute.Key, helper.AttributeEncode(attribute.Value));
            }

            return(new MvcHtmlString(output.ToString()));
        }
        public MvcHtmlString GetRegisteredLinks(HtmlHelper html)
        {
            var urlHelper = new UrlHelper(html.ViewContext.RequestContext, html.RouteCollection);

            var sb = new StringBuilder();

            foreach (var feed in _feeds)
            {
                var linkUrl = feed.IsExternal ?
                              feed.ExternalUrl :
                              urlHelper.RouteUrl(feed.RouteValues);
                sb.Append("\r\n<link rel=\"alternate\" type=\"application/" +
                          feed.Format.ToLowerInvariant() + "+xml\"");
                if (!string.IsNullOrEmpty(feed.Title))
                {
                    sb.Append(" title=\"" + html.AttributeEncode(feed.Title) + "\"");
                }
                sb.Append(" href=\"" + html.AttributeEncode(linkUrl) + "\"/>");
            }

            return(MvcHtmlString.Create(sb.ToString()));
        }
Example #16
0
        public static string SyndicationIcons(this HtmlHelper helper, string rssUrl, string atomUrl, string facebookUrl, string googlePlus)
        {
            StringBuilder html = new StringBuilder();

            if (!string.IsNullOrEmpty(rssUrl) || !string.IsNullOrEmpty(atomUrl))
            {
                UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

                html.Append("<div class=\"feed\">");

                Action <string, string> addIcon = (type, url) =>
                {
                    if (type == "G+")
                    {
                        html.Append(
                            " <a href=\"{0}\" style=\"text-decoration:none;\"><img src=\"https://ssl.gstatic.com/images/icons/gplus-32.png\" alt=\"\" style=\"border:0;width:24px;height:24px;\"/></a>"
                            .FormatWith(helper.AttributeEncode(url)));
                    }
                    else
                    {
                        string iconUrl = urlHelper.Image("{0}.png".FormatWith(type));

                        html.Append(" <a href=\"{0}\" target=\"_blank\"><img alt=\"{1}\" title=\"{1}\" src=\"{2}\"/></a>".FormatWith(helper.AttributeEncode(url), type, helper.AttributeEncode(iconUrl)));
                    }
                };

                if (!string.IsNullOrEmpty(atomUrl))
                {
                    addIcon("atom", atomUrl);
                }

                if (!string.IsNullOrEmpty(rssUrl))
                {
                    addIcon("rss", rssUrl);
                }

                if (!string.IsNullOrEmpty(facebookUrl))
                {
                    addIcon("facebook", facebookUrl);
                }

                if (!string.IsNullOrEmpty(googlePlus))
                {
                    addIcon("G+", googlePlus);
                }

                html.Append("</div>");
            }

            return(html.ToString());
        }
Example #17
0
    public static MvcHtmlString EditorForMany <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, IEnumerable <TValue> > > propertyExpression, Expression <Func <TValue, string> > indexResolverExpression = null, string htmlFieldName = null) where TModel : class
    {
        htmlFieldName = htmlFieldName ?? ExpressionHelper.GetExpressionText(propertyExpression);

        var items                           = propertyExpression.Compile()(html.ViewData.Model);
        var htmlBuilder                     = new StringBuilder();
        var htmlViewData                    = html.ViewData;
        var htmlTemplateInfo                = htmlViewData.TemplateInfo;
        var htmlFieldPrefix                 = htmlTemplateInfo.HtmlFieldPrefix;
        var htmlFieldNameWithPrefix         = html.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
        Func <TValue, string> indexResolver = null;

        if (indexResolverExpression == null)
        {
            indexResolver = x => null;
        }
        else
        {
            indexResolver = indexResolverExpression.Compile();
        }

        foreach (var item in items)
        {
            var dummy         = new { Item = item };
            var guid          = indexResolver(item);
            var memberExp     = Expression.MakeMemberAccess(Expression.Constant(dummy), dummy.GetType().GetProperty("Item"));
            var singleItemExp = Expression.Lambda <Func <TModel, TValue> >(memberExp, propertyExpression.Parameters);

            if (String.IsNullOrEmpty(guid))
            {
                guid = Guid.NewGuid().ToString();
            }
            else
            {
                guid = html.AttributeEncode(guid);
            }

            htmlBuilder.Append(String.Format(@"<input type=""hidden"" name=""{0}.Index"" value=""{1}"" />", htmlFieldNameWithPrefix, guid));

            if (indexResolverExpression != null)
            {
                htmlBuilder.Append(String.Format(@"<input type=""hidden"" name=""{0}[{1}].{2}"" value=""{1}"" />", htmlFieldNameWithPrefix, guid, ExpressionHelper.GetExpressionText(indexResolverExpression)));
            }

            htmlBuilder.Append(html.EditorFor(singleItemExp, null, String.Format("{0}[{1}]", htmlFieldName, guid)));
        }

        return(new MvcHtmlString(htmlBuilder.ToString()));
    }
Example #18
0
        public static MvcHtmlString UserAvatar <TModel>(this HtmlHelper <TModel> html, long userId, string username, bool userHasAvatar, string email)
        {
            var url = new UrlHelper(html.ViewContext.RequestContext);

            string imgUrl;

            if (userHasAvatar)
            {
                imgUrl = url.Action("ViewAvatar", "Images", new { id = userId });
            }
            else
            {
                imgUrl = "http://www.gravatar.com/avatar/" + HashString(email) + ".jpg?d=wavatar";
            }

            return(new MvcHtmlString("<img alt=\"" + html.AttributeEncode(username + "'s Avatar") + "\" src=\"" + html.AttributeEncode(imgUrl) + "\" />"));
        }
Example #19
0
        public static string HighlightLink(this HtmlHelper helper, string url)
        {
            var fullUrl = url;

            if (!url.Contains("://") && !url.StartsWith("mailto:"))
            {
                if (IsEmailUrl(url))
                {
                    fullUrl = "mailto:" + url;
                }
                else
                {
                    fullUrl = "http://" + url;
                }
            }
            return($"<a href=\"{helper.AttributeEncode(HttpUtility.HtmlDecode(fullUrl))}\">{url}</a>");
        }
Example #20
0
        public static MvcHtmlString StyledSelect(this HtmlHelper html, string name, IEnumerable <SelectListItem> items, object attributes, string rightImageUrl, int rightShadowWidth, string initValue)
        {
            // Use MVC input control value population precedence
            ModelState mState = html.ViewData.ModelState[name];
            string     val    = mState == null ? null : (mState.Value == null ? null : mState.Value.AttemptedValue);

            if (val == null && items.Any(i => i.Value == initValue))
            {
                val = initValue;
            }
            if (val == null)
            {
                object o = (string.IsNullOrEmpty(name) ? null : html.ViewData.Eval(name));
                val = (o == null ? null : o.ToString());
            }

            // Build HTML using passed-in attributes
            StringBuilder        sb    = new StringBuilder();
            RouteValueDictionary aDict = new RouteValueDictionary(attributes);

            aDict["class"] = (aDict["classes"] ?? "") + " l24-styled-dd";
            aDict.Remove("classes");
            aDict["style"] = "position: relative; display: inline-block; padding: 0px;" + (aDict["style"] ?? "");
            sb.AppendFormat("<span {0}><select name='{1}' style='margin: 0px; width: 100%; height: 100%; position: relative; z-index: 10; border: none; opacity: 0; -khtml-appearance: none; -webkit-appearance: none; filter: alpha(opacity=0); zoom: 1;'>",
                            aDict.Select(kvp => kvp.Key + "='" + html.AttributeEncode(kvp.Value) + "'").Join(" "),
                            name);
            items.Do(sli =>
                     sb.AppendFormat("<option value='{0}'{1}>{2}</option>",
                                     html.Encode(sli.Value),
                                     sli.Value == val ? " selected" : "",
                                     html.Encode(sli.Text))
                     );

            // the actually selected item
            SelectListItem selected = items.FirstOrDefault(sli => sli.Value == val);

            sb.AppendFormat("</select><span style='position: absolute; top: 0px; left: 0px; right: {0}px; bottom: 0px; z-index: 1; background: url({1}) no-repeat right; padding-left: 5px;'>{2}</span></span>",
                            -rightShadowWidth,
                            rightImageUrl,
                            (selected == null ? initValue : selected.Text) ?? "&nbsp;");
            MvcHtmlString s = MvcHtmlString.Create(sb.ToString());

            RegisterControlsScript(html);
            return(s);
        }
Example #21
0
 public static IHtmlString UrlLink(this HtmlHelper html, string url, string text, string @class = "")
 {
     if (string.IsNullOrEmpty(url) || (url.StartsWith("http") && url.Length < 8))
     {
         return(MvcHtmlString.Create(string.Format("<span class\"{0}\">{1}</span>",
                                                   @class,
                                                   html.Encode(text ?? string.Empty).Trim())
                                     ));
     }
     if (!url.StartsWith("http"))
     {
         url = "http://" + url;
     }
     return(MvcHtmlString.Create(string.Format("<a href=\"{0}\" class=\"{1}\">{2}</a>",
                                               html.AttributeEncode(url),
                                               @class,
                                               html.Encode(text ?? string.Empty).Trim()
                                               )));
 }
Example #22
0
        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText, string actionName, string controllerName, object htmlAttributes = null)
        {
            StringBuilder attr       = new StringBuilder();
            var           attributes = helper.AttributeEncode(htmlAttributes);
            string        UrlParam   = "";

            if (!string.IsNullOrEmpty(attributes))
            {
                attributes = attributes.Trim('{', '}');
                var attrValuePairs = attributes.Split(',');
                foreach (var attrValuePair in attrValuePairs)
                {
                    var      equalIndex = attrValuePair.IndexOf('=');
                    string[] attrValue  = attrValuePair.Split('=');
                    if (attrValuePair.Substring(0, equalIndex).Trim().ToLower() == "id")
                    {
                        UrlParam = attrValuePair.Substring(equalIndex + 1).Trim();
                    }
                    else
                    {
                        attr.AppendFormat("{0}='{1}' ", attrValuePair.Substring(0, equalIndex).Trim(), attrValuePair.Substring(equalIndex + 1).Trim());
                    }
                }
            }

            UrlHelper Url   = new UrlHelper(helper.ViewContext.RequestContext);
            string    route = Url.Content("~/" + controllerName + "/" + actionName + "/");

            if (!string.IsNullOrEmpty(UrlParam))
            {
                route += UrlParam;
            }

            StringBuilder html = new StringBuilder();

            html.AppendFormat("<button type='submit' formaction='{0}' {1}>{2}</button>", route, attr, buttonText);

            return(new MvcHtmlString(html.ToString()));
        }
Example #23
0
    public static MvcHtmlString MyValidationMessageFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper,
                                                                           Expression <Func <TModel, TProperty> > expression)
    {
        var propertyName = ExpressionHelper.GetExpressionText(expression);
        var fullName     = htmlHelper.AttributeEncode(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(propertyName));

        var isInvalid = htmlHelper.HasModelStateErros(expression);

        var errors = string.Empty;

        if (isInvalid)
        {
            foreach (var error in htmlHelper.ViewData.ModelState[fullName].Errors)
            {
                //add error message
                errors += error.ErrorMessage;
                break;
            }
        }

        return(MvcHtmlString.Create(errors));
    }
Example #24
0
        /// <summary>
        /// Generates a media type attribute suitable for an &lt;object&gt; or &lt;embed&gt; tag. The media type will be included in the CSP plugin-types directive.
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="mediaType">The media type.</param>
        public static IHtmlString CspMediaType(this HtmlHelper helper, string mediaType)
        {
            new Rfc2045MediaTypeValidator().Validate(mediaType);

            var context = helper.ViewContext.HttpContext;
            var cspConfigurationOverrideHelper = new CspConfigurationOverrideHelper();
            var headerOverrideHelper           = new HeaderOverrideHelper();

            var configOverride = new CspPluginTypesOverride()
            {
                Enabled = true, InheritMediaTypes = true, MediaTypes = new[] { mediaType }
            };

            cspConfigurationOverrideHelper.SetCspPluginTypesOverride(context, configOverride, false);
            cspConfigurationOverrideHelper.SetCspPluginTypesOverride(context, configOverride, true);

            headerOverrideHelper.SetCspHeaders(context, false);
            headerOverrideHelper.SetCspHeaders(context, true);
            var attribute = string.Format("type=\"{0}\"", helper.AttributeEncode(mediaType));

            return(new HtmlString(attribute));
        }
Example #25
0
        public static MvcHtmlString InputEditor(this HtmlHelper helper, string inputType, string buttonText, object htmlAttributes = null)
        {
            StringBuilder html = new StringBuilder();

            html.AppendFormat("<input type = '{0}' value = '{1}' ", inputType, buttonText);

            var attributes = helper.AttributeEncode(htmlAttributes);

            if (!string.IsNullOrEmpty(attributes))
            {
                attributes = attributes.Trim('{', '}');
                var attrValuePairs = attributes.Split(',');
                foreach (var attrValuePair in attrValuePairs)
                {
                    var equalIndex = attrValuePair.IndexOf('=');
                    var attrValue  = attrValuePair.Split('=');
                    html.AppendFormat("{0}='{1}' ", attrValuePair.Substring(0, equalIndex).Trim(), attrValuePair.Substring(equalIndex + 1).Trim());
                }
            }
            html.Append("/>");
            return(new MvcHtmlString(html.ToString()));
        }
Example #26
0
        public static MvcHtmlString AvatarImage(this HtmlHelper html, string filename, bool useThumbnail = true)
        {
            string tag = null;

            if (!String.IsNullOrWhiteSpace(filename))
            {
                var thumbConfig = useThumbnail ? "ThumbPath" : "MediumImagePath";

                var config    = ObjectFactory.GetInstance <IConfig>();
                var imagePath = VirtualPathUtility.Combine(VirtualPathUtility.ToAbsolute(config.GetSetting <string>("LargeImagePath")), filename);
                var thumbPath = VirtualPathUtility.Combine(VirtualPathUtility.ToAbsolute(config.GetSetting <string>(thumbConfig)), filename);
                tag = String.Format("<a class=\"fancy\" href=\"{0}\"><img class=\"avatar\" src=\"{1}\" /></a>", html.AttributeEncode(imagePath), html.AttributeEncode(thumbPath));
            }
            else
            {
                tag = String.Format("<img class=\"avatar\" src=\"{0}\" />", System.Web.VirtualPathUtility.ToAbsolute("~/content/images/no-image.gif"));
            }

            return(MvcHtmlString.Create(tag));
        }
Example #27
0
 public static string Image(this HtmlHelper helper, string fileName, string attributes)
 {
     fileName = string.Format("{0}", fileName);
     return(string.Format("<img src='{0}' '{1}' />", helper.AttributeEncode(fileName), helper.AttributeEncode(attributes)));
 }
 internal static string UrlTemplate(HtmlHelper html)
 {
     return String.Format(CultureInfo.InvariantCulture,
                          "<a href=\"{0}\">{1}</a>",
                          html.AttributeEncode(html.ViewContext.ViewData.Model),
                          html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue));
 }
Example #29
0
        private static HtmlString CreateNonceAttribute(HtmlHelper helper, string nonce)
        {
            var sb = "nonce=\"" + helper.AttributeEncode(nonce) + "\"";

            return(new HtmlString(sb));
        }
Example #30
0
        public static IHtmlString EmbedImage(this HtmlHelper html, string imagePathOrUrl, string alt = "")
        {
            if (string.IsNullOrWhiteSpace(imagePathOrUrl))
            {
                throw new ArgumentException("Path or URL required", "imagePathOrUrl");
            }

            if (IsFileName(imagePathOrUrl))
            {
                imagePathOrUrl = html.ViewContext.HttpContext.Server.MapPath(imagePathOrUrl);
            }
            var imageEmbedder = (ImageEmbedder)html.ViewData[ImageEmbedder.ViewDataKey];
            var resource      = imageEmbedder.ReferenceImage(imagePathOrUrl);

            return(new HtmlString(string.Format("<img src=\"cid:{0}\" alt=\"{1}\"/>", resource.ContentId, html.AttributeEncode(alt))));
        }
        internal static string UrlTemplate(HtmlHelper html, object attributes = null)
        {
            var dataAttributes = html.ViewContext.ViewData.ModelMetadata.AdditionalValues.GetDataAttributes();
            var customAttributes = html.ViewContext.ViewData.ModelMetadata.AdditionalValues.GetCustomAttributes();
            dataAttributes.MergeAttributes(customAttributes);

            TagBuilder mailTo = new TagBuilder("a");
            mailTo.MergeAttribute("href", html.AttributeEncode(html.ViewContext.ViewData.Model));
            mailTo.MergeAttributes(dataAttributes);
            mailTo.InnerHtml = html.Encode(html.ViewContext.ViewData.TemplateInfo.FormattedModelValue);

            return mailTo.ToString(TagRenderMode.Normal);
        }
Example #32
0
        public static string SyndicationIcons(this HtmlHelper helper, string rssUrl, string atomUrl)
        {
            StringBuilder html = new StringBuilder();

            if (!string.IsNullOrEmpty(rssUrl) || !string.IsNullOrEmpty(atomUrl))
            {
                UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

                html.Append("<div class=\"feed\">");

                Action <string, string> addIcon = (type, url) =>
                {
                    string iconUrl = urlHelper.Image("{0}.jpg".FormatWith(type));

                    html.Append(" <a href=\"{0}\" target=\"_blank\"><img alt=\"{1}\" title=\"{1}\" src=\"{2}\"/></a>".FormatWith(helper.AttributeEncode(url), type, helper.AttributeEncode(iconUrl)));
                };

                if (!string.IsNullOrEmpty(atomUrl))
                {
                    addIcon("atom", atomUrl);
                }

                if (!string.IsNullOrEmpty(rssUrl))
                {
                    addIcon("rss", rssUrl);
                }

                html.Append("</div>");
            }

            return(html.ToString());
        }