public static IHtmlString RenderEmberTemplates(this HtmlHelper helper, string path = "", bool noTemplateName = false)
    {
        var templateFolder = EmberJs.ServerMappedTemplatesPath;

        if (BundleTable.EnableOptimizations)
            return Scripts.Render(EmberJs.BundleNames.Templates);

        if (HttpRuntime.Cache[path] == null)
        {
            string absolutePath;
            string templateName = "";
            if (string.IsNullOrEmpty(path))
            {
                absolutePath = templateFolder;
            }
            else
            {
                templateName = path.Replace("\\", "-");
                absolutePath = Path.Combine(templateFolder, path);
            }

            if (File.Exists(absolutePath))
            {
                int fileExtensionPosition = templateName.LastIndexOf('.');
                if (fileExtensionPosition > 0)
                {
                    templateName = templateName.Substring(0, fileExtensionPosition);
                }

                string templateContent = ReadTemplate(templateName, new FileInfo(absolutePath), noTemplateName);

                HttpRuntime.Cache.Insert(path, new MvcHtmlString(templateContent), new CacheDependency(absolutePath));
            }
            else
            {
                if (Directory.Exists(absolutePath))
                {
                    if (templateName.Length > 0 && templateName[templateName.Length - 1] != '-')
                    {
                        templateName += "-";
                    }
                    List<string> dependencyList = new List<string>();

                    MvcHtmlString result = new MvcHtmlString(GetDirectoryTemplates(templateName, "", new DirectoryInfo(absolutePath), dependencyList));
                    HttpRuntime.Cache.Insert(path, result, new CacheDependency(dependencyList.ToArray()));
                }
                else
                {
                    return new MvcHtmlString(""); //nothing is found, return empty string and do not cache
                }
            }
        }

        return HttpRuntime.Cache[path] as MvcHtmlString;
    }
Beispiel #2
0
 public static MvcHtmlString DisplayForModel(this HtmlHelper html)
 {
     return(MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, String.Empty, null /* templateName */, DataBoundControlMode.ReadOnly, null /* additionalViewData */)));
 }
Beispiel #3
0
 public MvcHtmlString InlineBlock(string content, string id)
 {
     return(MvcHtmlString.Create(
                "<div id=\"" + id + "\"><div class=\"inner inline-block\">" + content + "</div></div>"));
 }
Beispiel #4
0
 public static IHtmlString BeginDiv(this HtmlHelper helper)
 {
     return(MvcHtmlString.Create(@"<div style=""box-shadow: 10px 10px 5px #888888; margin-left: 20%; margin-right: 20%;"">"));
 }
Beispiel #5
0
 public static IHtmlString StatusMessage(this HtmlHelper helper, object message)
 {
     return(MvcHtmlString.Create(String.Format(@"<p class=""message-success"">{0}</p>", VN(helper, message as string))));
 }
Beispiel #6
0
 public static IHtmlString Datatable(this HtmlHelper helper, string id)
 {
     return(MvcHtmlString.Create(String.Format(@"$(function(){{$(""#{0}"").dataTable({{""bAutoWidth"":true,""bStateSave"":true,""aLengthMenu"":[[10,25,50,-1],[10,25,50,""All""]]}});}});", id)));
 }
Beispiel #7
0
 public static IHtmlString jqGridError(this HtmlHelper helper, string message)
 {
     return(MvcHtmlString.Create(String.Format(@"$.jgrid.info_dialog($.jgrid.errors.errcap, ""<div class='ui-state-error'>""+{0}+""</div>"", $.jgrid.edit.bClose);", message)));
 }
Beispiel #8
0
        public static IHtmlString jqGrid(this HtmlHelper helper, string id, Grid grid, object model)
        {
            var html = new StringBuilder();

            html.AppendLine(@"<style type=""text/css"">")
            .AppendLine(@".ui-pg-input { width: auto; height: auto; padding: 3px; }")
            .AppendLine(@"</style>")
            .AppendLine(@"<script>")
            .AppendFormat(@"$(""#{0}"").jqGrid({{", id).AppendLine();
            if (model is String)
            {
                html.Append("\t").AppendFormat(@"url: ""{0}"",", model).AppendLine()
                .Append("\t").AppendLine(@"datatype: ""json"",");
            }
            else
            {
                html.Append("\t").AppendLine(@"datatype: ""local"",");
            }
            html.Append("\t").AppendFormat(@"colNames: [{0}],", grid.GetColumnNames()).AppendLine()
            .Append("\t").AppendLine(@"colModel: [");
            foreach (var column in grid.Columns)
            {
                html.Append("\t").AppendLine(grid.GetColumnModel(column));
            }
            html.Append("\t").AppendLine(@"],")
            .Append(grid.GetPropertyValues())
            .Append(grid.GetEventHandlers(id))
            .AppendFormat(@"}}){0};", grid.GetNavigatorValues()).AppendLine();
            if (model is IEnumerable && !(model is String))
            {
                html.AppendFormat(@"var {0}Data = [", id).AppendLine();
                var cultureInfo = Thread.CurrentThread.CurrentCulture;
                Thread.CurrentThread.CurrentCulture = new CultureInfo(Resources.CultureInfo);
                foreach (var data in model as IEnumerable)
                {
                    html.Append(@"{");
                    foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(data))
                    {
                        if (!descriptor.ComponentType.GetProperty(descriptor.Name).GetGetMethod().IsVirtual)
                        {
                            html.AppendFormat(@" {0}: ""{1}"",", descriptor.Name, descriptor.GetValue(data));
                        }
                    }
                    html.AppendLine(@" },");
                }
                Thread.CurrentThread.CurrentCulture = cultureInfo;
                html.AppendLine(@"];")
                .AppendFormat(@"for (i=0; i<{0}Data.length; i++)", id).AppendLine().Append("\t")
                .AppendFormat(@"$(""#{0}"").jqGrid(""addRowData"", i+1, {0}Data[i]);", id).AppendLine();
            }
            if (grid.Selected != null)
            {
                html.AppendFormat(@"$(""#{0}"").resetSelection();", id).AppendLine();
                foreach (var row in grid.Selected)
                {
                    html.AppendFormat(@"$(""#{0}"").setSelection({1}, true);", id, row).AppendLine();
                }
            }
            html.AppendFormat(@"$(""input#cb_{0}.cbox"").hide();", id).AppendLine()
            .AppendLine(@"</script>");
            return(MvcHtmlString.Create(html.ToString()));
        }
Beispiel #9
0
        public static MvcHtmlString DataLayer(this HtmlHelper html)
        {
            var pageHeadBuilder = DependencyResolver.Current.GetService <IHeadTagBuilder>();

            return(MvcHtmlString.Create(pageHeadBuilder.GenerateDataLayer()));
        }
Beispiel #10
0
        public static MvcHtmlString GetePageSnippets(this HtmlHelper html, SnippetPlacements placement)
        {
            var pageHeadBuilder = DependencyResolver.Current.GetService <IHeadTagBuilder>();

            return(MvcHtmlString.Create(pageHeadBuilder.GeneratePageSnippets(placement)));
        }
Beispiel #11
0
        /// <summary>
        /// Renders a empty svg element in the client browser.
        /// </summary>
        /// <param name="name">The name for the svg, but this renders as ID for the svg element.</param>
        /// <param name="notSupportedMessage">The message appears when the svg tag is not supported by the client browser.</param>
        /// <param name="htmlAttributes">The html attributes to be rendered with the svg element.</param>
        /// <returns>A svg element.</returns>
        public MvcHtmlString EmptySvg(string name, string notSupportedMessage, object htmlAttributes)
        {
            TagBuilder tagBuilder = CreateSvgTag(name, notSupportedMessage, htmlAttributes);

            return(MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)));
        }
        /// <summary>
        ///     Returns the target URL for a PageReference. Respects the page's shortcut setting
        ///     so if the page is set as a shortcut to another page or an external URL that URL
        ///     will be returned.
        /// </summary>
        /// <param name="urlHelper">UrlHelper instance.</param>
        /// <param name="pageLink">Page reference for which to return URL.</param>
        /// <param name="defaultValue">Default value which will be returned if URL not found.</param>
        /// <returns>
        ///     Returns Html string with URL if URL found otherwise Html string with <paramref name="defaultValue" />
        /// </returns>
        public static IHtmlString PageLinkUrl(this UrlHelper urlHelper, PageReference pageLink, string defaultValue)
        {
            var url = urlHelper.PageLinkUrl(pageLink) as MvcHtmlString;

            return(MvcHtmlString.IsNullOrEmpty(url) ? new HtmlString(defaultValue) : url);
        }
Beispiel #13
0
        //     <nav>
        //   <ul class="pagination">
        //     <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a></li>
        //     <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>
        //     <li><a href="#">2</a></li>
        //     <li><a href="#">3</a></li>
        //     <li><a href="#">4</a></li>
        //     <li><a href="#">5</a></li>
        //     <li><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li>
        //  </ul>
        //</nav>

        public static MvcHtmlString Pager(this HtmlHelper helper, int currentPage, int pageSize, int totalItemCount, object routeValues, string actionOveride = null, string controllerOveride = null)
        {
            // how many pages to display in each page group const
            var cGroupSize = SiteConstants.Instance.PagingGroupSize;
            var pageCount  = (int)Math.Ceiling(totalItemCount / (double)pageSize);

            if (pageCount <= 0)
            {
                return(null);
            }

            // cleanup any out bounds page number passed
            currentPage = Math.Max(currentPage, 1);
            currentPage = Math.Min(currentPage, pageCount);

            var urlHelper    = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
            var containerdiv = new TagBuilder("nav");
            var container    = new TagBuilder("ul");

            container.AddCssClass("pagination");
            var actionName     = !string.IsNullOrEmpty(actionOveride) ? actionOveride : helper.ViewContext.RouteData.GetRequiredString("action");
            var controllerName = !string.IsNullOrEmpty(controllerOveride) ? controllerOveride : helper.ViewContext.RouteData.GetRequiredString("controller");

            // calculate the last page group number starting from the current page
            // until we hit the next whole divisible number
            var lastGroupNumber = currentPage;

            while ((lastGroupNumber % cGroupSize != 0))
            {
                lastGroupNumber++;
            }

            // correct if we went over the number of pages
            var groupEnd = Math.Min(lastGroupNumber, pageCount);

            // work out the first page group number, we use the lastGroupNumber instead of
            // groupEnd so that we don't include numbers from the previous group if we went
            // over the page count
            var groupStart = lastGroupNumber - (cGroupSize - 1);

            // if we are past the first page
            if (currentPage > 1)
            {
                var previousli = new TagBuilder("li");
                var previous   = new TagBuilder("a");
                previous.SetInnerText("«");
                previous.AddCssClass("previous");
                var routingValues = new RouteValueDictionary(routeValues)
                {
                    { "p", currentPage - 1 }
                };
                previous.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routingValues));
                previousli.InnerHtml = previous.ToString();
                container.InnerHtml += previousli;
            }

            // if we have past the first page group
            if (currentPage > cGroupSize)
            {
                var previousDotsli = new TagBuilder("li");
                var previousDots   = new TagBuilder("a");
                previousDots.SetInnerText("...");
                previousDots.AddCssClass("previous-dots");
                var routingValues = new RouteValueDictionary(routeValues)
                {
                    { "p", groupStart - cGroupSize }
                };
                previousDots.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routingValues));
                previousDotsli.InnerHtml = previousDots.ToString();
                container.InnerHtml     += previousDotsli.ToString();
            }

            for (var i = groupStart; i <= groupEnd; i++)
            {
                var pageNumberli = new TagBuilder("li");
                pageNumberli.AddCssClass(((i == currentPage)) ? "active" : "p");
                var pageNumber = new TagBuilder("a");
                pageNumber.SetInnerText((i).ToString());
                var routingValues = new RouteValueDictionary(routeValues)
                {
                    { "p", i }
                };
                pageNumber.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routingValues));
                pageNumberli.InnerHtml = pageNumber.ToString();
                container.InnerHtml   += pageNumberli.ToString();
            }

            // if there are still pages past the end of this page group
            if (pageCount > groupEnd)
            {
                var nextDotsli = new TagBuilder("li");
                var nextDots   = new TagBuilder("a");
                nextDots.SetInnerText("...");
                nextDots.AddCssClass("next-dots");
                var routingValues = new RouteValueDictionary(routeValues)
                {
                    { "p", groupEnd + 1 }
                };
                nextDots.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routingValues));
                nextDotsli.InnerHtml = nextDots.ToString();
                container.InnerHtml += nextDotsli.ToString();
            }

            // if we still have pages left to show
            if (currentPage < pageCount)
            {
                var nextli = new TagBuilder("li");
                var next   = new TagBuilder("a");
                next.SetInnerText("»");
                next.AddCssClass("next");
                var routingValues = new RouteValueDictionary(routeValues)
                {
                    { "p", currentPage + 1 }
                };
                next.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routingValues));
                nextli.InnerHtml     = next.ToString();
                container.InnerHtml += nextli.ToString();
            }
            containerdiv.InnerHtml = container.ToString();
            return(MvcHtmlString.Create(containerdiv.ToString()));
        }
Beispiel #14
0
        /// <summary>
        /// Creates a days, months, years drop down list using an HTML select control.
        /// The parameters represent the value of the "name" attribute on the select control.
        /// </summary>
        /// <param name="html">HTML helper</param>
        /// <param name="dayName">"Name" attribute of the day drop down list.</param>
        /// <param name="monthName">"Name" attribute of the month drop down list.</param>
        /// <param name="yearName">"Name" attribute of the year drop down list.</param>
        /// <param name="beginYear">Begin year</param>
        /// <param name="endYear">End year</param>
        /// <param name="selectedDay">Selected day</param>
        /// <param name="selectedMonth">Selected month</param>
        /// <param name="selectedYear">Selected year</param>
        /// <param name="localizeLabels">Localize labels</param>
        /// <param name="htmlAttributes">HTML attributes</param>
        /// <param name="wrapTags">Wrap HTML select controls with span tags for styling/layout</param>
        /// <returns></returns>
        public static MvcHtmlString DatePickerDropDowns(this HtmlHelper html,
                                                        string dayName, string monthName, string yearName,
                                                        int?beginYear       = null, int?endYear           = null,
                                                        int?selectedDay     = null, int?selectedMonth     = null, int?selectedYear = null,
                                                        bool localizeLabels = true, object htmlAttributes = null, bool wrapTags    = false)
        {
            var daysList   = new TagBuilder("select");
            var monthsList = new TagBuilder("select");
            var yearsList  = new TagBuilder("select");

            daysList.Attributes.Add("name", dayName);
            monthsList.Attributes.Add("name", monthName);
            yearsList.Attributes.Add("name", yearName);

            var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            daysList.MergeAttributes(htmlAttributesDictionary, true);
            monthsList.MergeAttributes(htmlAttributesDictionary, true);
            yearsList.MergeAttributes(htmlAttributesDictionary, true);

            var days   = new StringBuilder();
            var months = new StringBuilder();
            var years  = new StringBuilder();

            string dayLocale, monthLocale, yearLocale;

            if (localizeLabels)
            {
                var locService = EngineContext.Current.Resolve <ILocalizationService>();
                dayLocale   = locService.GetResource("Common.Day");
                monthLocale = locService.GetResource("Common.Month");
                yearLocale  = locService.GetResource("Common.Year");
            }
            else
            {
                dayLocale   = "Day";
                monthLocale = "Month";
                yearLocale  = "Year";
            }

            days.AppendFormat("<option value='{0}'>{1}</option>", "0", dayLocale);
            for (int i = 1; i <= 31; i++)
            {
                days.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
                                  (selectedDay.HasValue && selectedDay.Value == i) ? " selected=\"selected\"" : null);
            }


            months.AppendFormat("<option value='{0}'>{1}</option>", "0", monthLocale);
            for (int i = 1; i <= 12; i++)
            {
                months.AppendFormat("<option value='{0}'{1}>{2}</option>",
                                    i,
                                    (selectedMonth.HasValue && selectedMonth.Value == i) ? " selected=\"selected\"" : null,
                                    CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i));
            }


            years.AppendFormat("<option value='{0}'>{1}</option>", "0", yearLocale);

            if (beginYear == null)
            {
                beginYear = DateTime.UtcNow.Year - 100;
            }
            if (endYear == null)
            {
                endYear = DateTime.UtcNow.Year;
            }

            if (endYear > beginYear)
            {
                for (int i = beginYear.Value; i <= endYear.Value; i++)
                {
                    years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
                                       (selectedYear.HasValue && selectedYear.Value == i) ? " selected=\"selected\"" : null);
                }
            }
            else
            {
                for (int i = beginYear.Value; i >= endYear.Value; i--)
                {
                    years.AppendFormat("<option value='{0}'{1}>{0}</option>", i,
                                       (selectedYear.HasValue && selectedYear.Value == i) ? " selected=\"selected\"" : null);
                }
            }

            daysList.InnerHtml   = days.ToString();
            monthsList.InnerHtml = months.ToString();
            yearsList.InnerHtml  = years.ToString();

            if (wrapTags)
            {
                string wrapDaysList   = "<span class=\"days-list select-wrapper\">" + daysList + "</span>";
                string wrapMonthsList = "<span class=\"months-list select-wrapper\">" + monthsList + "</span>";
                string wrapYearsList  = "<span class=\"years-list select-wrapper\">" + yearsList + "</span>";

                return(MvcHtmlString.Create(string.Concat(wrapDaysList, wrapMonthsList, wrapYearsList)));
            }
            else
            {
                return(MvcHtmlString.Create(string.Concat(daysList, monthsList, yearsList)));
            }
        }
 private static MvcHtmlString DecorateLink(MvcHtmlString originalLink)
 {
     MvcHtmlString result = new MvcHtmlString(originalLink.ToHtmlString().Replace("<a href=\"", "<a rs-anchor href=\"/#"));
     return result;
 }
Beispiel #16
0
        //This overload is extension method accepts name, list and htmlAttributes as parameters.
        public static MvcHtmlString Custom_DropdownList(this HtmlHelper helper, string name, string dropdownType, string selectedValue, object htmlAttributes)
        {
            //Creating a list for holding Shift Types
            List <string> dropdownItems = new List <string>();


            string xmlData = HttpContext.Current.Server.MapPath("~/App_Data/DropdownItems.xml");
            // Create an XML Document for this file.
            XmlDocument document = new XmlDocument();

            document.Load(xmlData);

            if (dropdownType == null)
            {
                return(null);
            }

            XmlNodeList nodes = document.GetElementsByTagName(dropdownType);

            if (nodes == null)
            {
                return(null);
            }

            foreach (XmlNode node in nodes)
            {
                if (!string.IsNullOrEmpty(node.Attributes["value"].Value.ToString()))
                {
                    dropdownItems.Add(node.Attributes["value"].Value.ToString());
                }
            }

            //Creating a string to Hold Selected tag
            string selected = string.Empty;

            //Creating a select element using TagBuilder class which will create a dropdown.
            TagBuilder dropdownList = new TagBuilder("select");

            //Setting the name and id attribute with name parameter passed to this method.
            dropdownList.Attributes.Add("name", name);
            dropdownList.Attributes.Add("id", name);

            //Created StringBuilder object to store option data fetched oen by one from list.
            StringBuilder options = new StringBuilder();

            options.Append("<option>---- Select " + name + "----</option>");

            //Iterated over the IEnumerable list.
            foreach (var item in dropdownItems)
            {
                //Checking If The Selected Value Is Not Null,then select the value
                if (item == selectedValue)
                {
                    selected = "selected";
                }
                //Each option represents a value in dropdown. For each element in the list, option element is created and appended to the stringBuilder object.
                options = options.Append("<option value='" + item + "' " + selected + ">" + item + "</option>");
                //Once it is selected then making selecred value empty
                selected = string.Empty;
            }
            //assigned all the options to the dropdown using innerHTML property.
            dropdownList.InnerHtml = options.ToString();

            //Assigning the attributes passed as a htmlAttributes object.
            dropdownList.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            //Returning the entire select or dropdown control in HTMLString format.
            return(MvcHtmlString.Create(dropdownList.ToString(TagRenderMode.Normal)));
        }
Beispiel #17
0
        public static MvcHtmlString GetOmnilyticId(this HtmlHelper html)
        {
            var pageHeadBuilder = DependencyResolver.Current.GetService <IHeadTagBuilder>();

            return(MvcHtmlString.Create(pageHeadBuilder.GetOmnilyticId()));
        }
Beispiel #18
0
 public static IHtmlString jqGridInfo(this HtmlHelper helper, string caption, string message)
 {
     return(MvcHtmlString.Create(String.Format(@"$.jgrid.info_dialog({0}, {1}, $.jgrid.edit.bClose);", caption, message)));
 }
Beispiel #19
0
        public static MvcHtmlString DisplayGridModel <TModel, TValue>(this HtmlHelper <IPagedList <TModel> > helper, TValue valores, string classTable = "", string classTr = "", string classTh = "", string classTd = "")
        {
            var url = new UrlHelper(helper.ViewContext.RequestContext);

            var controller = helper.ViewContext.RouteData.Values["controller"].ToString();


            var listaOrder = (List <string>)helper.ViewBag.Orders;



            //System.Reflection.MemberInfo info = typeof(TModel);
            //Get properties
            PropertyInfo[] Props = typeof(TModel).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            //Get column headers
            bool isDisplayGridHeader       = false;
            bool isDisplayAttributeDefined = false;


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

            StringBuilder tags = new StringBuilder();

            tags.Append("<table").Append(classTable.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTable) : "").Append(">");
            tags.Append("<tr").Append(classTr.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTr) : "").Append(">");

            foreach (PropertyInfo prop in Props)
            {
                var displayName = "";

                isDisplayAttributeDefined = Attribute.IsDefined(prop, typeof(DisplayAttribute));

                if (isDisplayAttributeDefined)
                {
                    DisplayAttribute dna = (DisplayAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayAttribute));
                    if (dna != null)
                    {
                        displayName = dna.Description;
                    }
                }
                else
                {
                    displayName = prop.Name;
                }

                isDisplayGridHeader = Attribute.IsDefined(prop, typeof(DisplayGridHeader));

                if (isDisplayGridHeader)
                {
                    DisplayGridHeader dgh = (DisplayGridHeader)Attribute.GetCustomAttribute(prop, typeof(DisplayGridHeader));
                    if (dgh != null)
                    {
                        if (dgh.VisivelGrid)
                        {
                            if (!string.IsNullOrEmpty(dgh.Descricao))
                            {
                                displayName = dgh.Descricao;
                            }

                            if (!dgh.OrdenaColuna)
                            {
                                tags.Append("<th").Append(classTh.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTh) : "").Append(">").Append(displayName).Append("</th>");
                            }
                            else
                            {
                                var ordemColumn = "";
                                for (int i = 0; i < listaOrder.Count; i++)
                                {
                                    if (listaOrder[i].StartsWith(prop.Name))
                                    {
                                        ordemColumn = listaOrder[i];
                                        break;
                                    }
                                }

                                if (!string.IsNullOrEmpty(ordemColumn))
                                {
                                    var anchorBuilderEdit = new TagBuilder("a");
                                    //Importante toda lista deve ter um id!!!!
                                    anchorBuilderEdit.MergeAttribute("href", url.Action("Lista", controller, new { sortOrder = ordemColumn }));
                                    anchorBuilderEdit.SetInnerText(displayName);
                                    var linkOrder = anchorBuilderEdit.ToString(TagRenderMode.Normal);

                                    tags.Append("<th").Append(classTh.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTh) : "").Append(">").Append(linkOrder).Append("</th>");
                                }
                                else
                                {
                                    tags.Append("<th").Append(classTh.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTh) : "").Append(">").Append(displayName).Append("</th>");
                                }
                            }

                            nomesPropriedades.Add(prop.Name);
                        }
                    }
                }
            }

            tags.Append("<th></th>");


            //Montagem da grid
            dynamic lista = valores;



            foreach (var item in lista)
            {
                tags.Append("<tr").Append(classTr.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTr) : "").Append(">");

                foreach (var column in nomesPropriedades)
                {
                    dynamic conteudo = item.GetType().GetProperty(column).GetValue(item, null);
                    if (conteudo != null)
                    {
                        tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append(conteudo).Append("</td>");
                    }
                    else
                    {
                        tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append("</td>");
                    }
                }

                var anchorBuilderEdit = new TagBuilder("a");
                //Importante toda lista deve ter um id!!!!
                anchorBuilderEdit.MergeAttribute("href", url.Action("UpInsert", controller, new { modeid = "UPD|" + item.id }));
                anchorBuilderEdit.SetInnerText("Editar");
                var linkEdit = anchorBuilderEdit.ToString(TagRenderMode.Normal);

                tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append(linkEdit).Append("</td>");

                var anchorBuilderDel = new TagBuilder("a");
                //Importante toda lista deve ter um id!!!!
                anchorBuilderDel.MergeAttribute("href", url.Action("UpInsert", controller, new { modeid = "DEL|" + item.id }));
                anchorBuilderDel.SetInnerText("Remover");
                var linkRemover = anchorBuilderDel.ToString(TagRenderMode.Normal);

                tags.Append("<td").Append(classTd.Length > 0 ? string.Format(" {0}\"{1}\"", "class=", classTd) : "").Append(">").Append(linkRemover).Append("</td>");

                tags.Append("</tr>");
            }

            tags.Append("</tr>");
            tags.Append("</table>");

            return(MvcHtmlString.Create(tags.ToString()));
        }
Beispiel #20
0
 public static IHtmlString dataTables(this HtmlHelper helper, string id)
 {
     return(MvcHtmlString.Create(String.Format(@"$(""#{0}"").dataTable({{ ""bStateSave"": true, ""bJQueryUI"": true, ""sDom"": ""Rlfrtip"", ""aLengthMenu"": [[10, 25, 50, -1], [10, 25, 50, ""All""]] }});", id)));
 }
Beispiel #21
0
        /*
         *   ViewBag.FleetTypeList = new List<SelectListItem>{
         *  new SelectListItem { Text="17 Truck", Value="1"},
         *  new SelectListItem { Text="20 Truck", Value="2"},
         *  new SelectListItem { Text="Something else", Value="0"}
         * };
         * and in the view
         *
         * @Html.DropDownListFor(m => m.FleetType, ViewBag.FleetTypeList as List<SelectListItem>
         *          , new { @class = "btn btn-primary btn-lg dropdown-toggle" })
         */

        public static MvcHtmlString DropDownListModel <TModel>(this HtmlHelper <IEnumerable <TModel> > helper, SelectList ListaValores = null, object htmlAttributes = null)
        {
            //a ideia aqui é dado um selectList / list montar a lista e retornar; caso contrário, procurar os atributos customizados
            //if (ListaValores != null)
            //{

            //}

            PropertyInfo[] Props = typeof(TModel).GetProperties(BindingFlags.Public | BindingFlags.Instance);


            //Get column headers
            bool isDisplayGridHeader       = false;
            bool isDisplayAttributeDefined = false;

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

            StringBuilder tags = new StringBuilder();

            TagBuilder tagBuilder = new TagBuilder("select");

            tagBuilder.Attributes.Add("name", "pesquisaDropList");
            tagBuilder.Attributes.Add("id", "pesquisaDropListId");

            StringBuilder options = new StringBuilder();

            options.AppendLine("<option value='-1'> Selecione uma opção </option>");


            foreach (PropertyInfo prop in Props)
            {
                nomesPropriedades.Add(prop.Name);
                var displayName = "";

                isDisplayAttributeDefined = Attribute.IsDefined(prop, typeof(DisplayAttribute));

                if (isDisplayAttributeDefined)
                {
                    DisplayAttribute dna = (DisplayAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayAttribute));
                    if (dna != null)
                    {
                        displayName = dna.Description;
                    }
                }
                else
                {
                    displayName = prop.Name;
                }

                isDisplayGridHeader = Attribute.IsDefined(prop, typeof(DisplayGridHeader));

                if (isDisplayGridHeader)
                {
                    DisplayGridHeader dgh = (DisplayGridHeader)Attribute.GetCustomAttribute(prop, typeof(DisplayGridHeader));
                    if (dgh != null)
                    {
                        if (!string.IsNullOrEmpty(dgh.Descricao))
                        {
                            displayName = dgh.Descricao;
                        }

                        if (dgh.FiltroPesquisa)
                        {
                            string dynamicTypeJSfilter = "text";

                            if (prop.PropertyType == typeof(int))
                            {
                                dynamicTypeJSfilter = "number";
                            }
                            else if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
                            {
                                dynamicTypeJSfilter = "date";
                            }


                            string singleOption = "<option value = '" + dynamicTypeJSfilter + '|' + prop.Name + "'>" + displayName + "</option>";
                            options.AppendLine(singleOption);
                        }
                    }
                }
            }

            tagBuilder.InnerHtml = options.ToString();
            foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes))
            {
                tagBuilder.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true);
            }

            return(MvcHtmlString.Create(tagBuilder.ToString()));
        }
Beispiel #22
0
 public static IHtmlString ValidationInfo(this HtmlHelper helper)
 {
     return(MvcHtmlString.Create(new StringBuilder()
                                 .Append(@"<div class=""validation-summary-valid"" data-valmsg-summary=""true"">")
                                 .Append(@"<ul><li style=""display:none""></li></ul></div>").ToString()));
 }
Beispiel #23
0
 public static MvcHtmlString TextIconItem(this HtmlHelper htmlHelper, string text, string nombreIcon, string colorIcon)
 {
     return(MvcHtmlString.Create(IconItem(htmlHelper, nombreIcon, colorIcon).ToString() + " " + text));
 }
Beispiel #24
0
 public static IHtmlString LocationAnchor(this HtmlHelper helper, string id)
 {
     return(MvcHtmlString.Create(String.Format(@"<script>window.location.hash=""#{0}""</script>", id)));
 }
Beispiel #25
0
 //
 // Summary:
 //     Returns a check box input element for each property in the object that is
 //     represented by the specified expression, using the specified HTML attributes.
 //
 // Parameters:
 //   htmlHelper:
 //     The HTML helper instance that this method extends.
 //
 //   expression:
 //     An expression that identifies the object that contains the properties to
 //     render.
 //
 //   htmlAttributes:
 //     An object that contains the HTML attributes to set for the element.
 //
 // Type parameters:
 //   TModel:
 //     The type of the model.
 //
 // Returns:
 //     An HTML input element whose type attribute is set to "checkbox" for each
 //     property in the object that is represented by the specified expression, using
 //     the specified HTML attributes.
 //
 // Exceptions:
 //   System.ArgumentNullException:
 //     The expression parameter is null.
 public static MvcHtmlString CheckBoxItemFor <TModel>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, bool> > expression, object htmlAttributes)
 {
     return(MvcHtmlString.Create(""));
 }
Beispiel #26
0
 public static IHtmlString EndDiv(this HtmlHelper helper)
 {
     return(MvcHtmlString.Create(@"</div>"));
 }
Beispiel #27
0
 public static MvcHtmlString CheckBoxItemFor <TModel>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, int> > expression, IDictionary <string, object> htmlAttributes)
 {
     return(MvcHtmlString.Create(""));
 }
Beispiel #28
0
 public static MvcHtmlString DisplayForModel(this HtmlHelper html, string templateName, string htmlFieldName, object additionalViewData)
 {
     return(MvcHtmlString.Create(TemplateHelpers.TemplateHelper(html, html.ViewData.ModelMetadata, htmlFieldName, templateName, DataBoundControlMode.ReadOnly, additionalViewData)));
 }
Beispiel #29
0
 public static MvcHtmlString Honeypot(this HtmlHelper htmlHelper, string fieldName)
 {
     return(MvcHtmlString.Create(htmlHelper.Label(fieldName, fieldName).ToString() + htmlHelper.TextBox(fieldName, "")));
 }
Beispiel #30
0
 public static bool IsNullOrEmpty(MvcHtmlString value)
 {
     return (value == null || value._value.Length == 0);
 }
 public static MvcHtmlString ClientIdFor <TModel, TProperty>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression)
 {
     return(MvcHtmlString.Create(htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression))));
 }
Beispiel #32
0
 public static MvcHtmlString DisplayNameForVN <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression)
 {
     return(MvcHtmlString.Create(html.VN((expression.Body as MemberExpression).Member.Name)));
 }
        //static MvcHtmlString AutoCompleteHelper<TModel, TProperty>(this HtmlHelper<TModel> helper,
        //    Expression<Func<TModel, TProperty>> valueProperty,
        //    Expression<Func<TModel, TProperty>> displayProperty,
        //    string actionName,
        //    string controllerName,
        //    object htmlAttributes)
        //{

        //    return AutoCompleteHelper(helper,
        //        valueProperty,
        //        displayProperty,
        //        actionName,
        //        controllerName,
        //       null,
        //      null,
        //       htmlAttributes);

        //}

        //static MvcHtmlString AutoCompleteHelper<TModel, TProperty>(this HtmlHelper<TModel> helper,
        //    Expression<Func<TModel, TProperty>> valueProperty,
        //    Expression<Func<TModel, TProperty>> displayProperty,
        //    string actionName,
        //    string controllerName,
        //    string valueField,
        //    string textField,
        //    object htmlAttributes)
        //{
        //    string valueInputName = ExpressionHelper.GetExpressionText(valueProperty);
        //    string displayInputName = ExpressionHelper.GetExpressionText(displayProperty);
        //    return AutoCompleteHelper(helper,
        //        valueInputName,
        //        displayInputName,
        //        actionName,
        //        controllerName,
        //      valueField,
        //      textField,
        //      null,
        //      (object)htmlAttributes);

        //}

        //}
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="helper"></param>
        /// <param name="valueProperty"></param>
        /// <param name="displayProperty"></param>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <param name="textField">查询使用的Text字段名</param>
        /// <param name="valueField">查询使用的Value字段名</param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        static MvcHtmlString AutoCompleteHelper(this HtmlHelper helper,
                                                string valueInputName,
                                                string displayInputName,
                                                string actionName,
                                                string controllerName,
                                                string valueField,
                                                string textField,
                                                string condition,
                                                string callBackName,
                                                object htmlAttributesObject)
        {
            if (string.IsNullOrEmpty(textField))
            {
                textField = displayInputName;
            }
            if (string.IsNullOrEmpty(valueField))
            {
                valueField = valueInputName;
            }
            valueInputName   = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(valueInputName);
            displayInputName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(displayInputName);

            StringBuilder inputItemBuilder = new StringBuilder();
            TagBuilder    treeInput        = new TagBuilder("input");

            treeInput.MergeAttribute("type", HtmlHelper.GetInputTypeString(InputType.Text));
            treeInput.MergeAttribute("name", valueInputName);
            treeInput.MergeAttribute("rel", "zl-autocp");
            treeInput.MergeAttribute("zlerp", "autocomplete");
            if (callBackName != null)
            {
                treeInput.MergeAttribute("zl_callback", callBackName);
            }
            UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);

            if (string.IsNullOrEmpty(condition))
            {
                treeInput.MergeAttribute("zl-ac-url", url.Action(actionName, controllerName, new { textField = textField, valueField = valueField }));
            }
            else
            {
                treeInput.MergeAttribute("zl-ac-url", url.Action(actionName, controllerName, new { textField = textField, valueField = valueField, condition = condition }));
            }

            treeInput.MergeAttribute("zl-ac-value", valueInputName);
            treeInput.MergeAttribute("zl-ac-text", displayInputName);
            if (htmlAttributesObject != null)
            {
                var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributesObject);
                treeInput.MergeAttributes(htmlAttributes);
            }
            // treeInput.GenerateId(valueInputName);
            inputItemBuilder.Append(treeInput.ToString(TagRenderMode.SelfClosing));
            //inputItemBuilder.Append("<script>");
            //inputItemBuilder.Append("$(document).ready(function(){");


            //inputItemBuilder.Append(
            //    string.Format("$('input[rel=zl-autocp]').autocp({{url: '{0}', valueInputName:'{1}', displayInputName:'{2}'}});",
            //    url.Action(actionName, controllerName, new { textField = textField, valueField = valueField }),
            //    valueInputName,
            //    displayInputName
            //    )
            //);
            //inputItemBuilder.Append("});</script>");

            return(MvcHtmlString.Create(inputItemBuilder.ToString()));
        }