public static MvcHtmlString ActionlinkWithSpanForIcon(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes, string spanAttributes)
        {
            string strActionLink = LinkExtensions.ActionLink(htmlHelper, linkText, actionName, routeValues, htmlAttributes).ToString();

            /*var sb = new StringBuilder();
             * sb.Append(string.Format("<span class='{0}'></span>{1}", spanAttributes, linkText));*/
            strActionLink = strActionLink.Replace(linkText, string.Format("<span class='{0}'></span>{1}", spanAttributes, linkText));

            /*if (routeValues != null)
             * {
             *  RouteValueDictionary rvd = new RouteValueDictionary(routeValues);
             *  if (rvd.Count > 0)
             *  {
             *      sb.Append("/?");
             *      foreach (var rv in rvd)
             *      {
             *          sb.Append(rv.Key.ToString() + "=" + rv.Value + "&");
             *      }
             *      sb.Remove(sb.Length - 1, 1);
             *  }
             * }
             * TagBuilder spanBuilder = new TagBuilder("a");
             * if (routeValues != null)
             * {
             *  spanBuilder.Attributes.Add("href", string.Format("/{0}{1}",  actionName, sb.ToString()));
             * }
             * spanBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
             * spanBuilder.InnerHtml = string.Format("<span class='{0}'></span>{1}", spanAttributes, linkText);*/

            return(MvcHtmlString.Create(strActionLink));
        }
        public static MvcHtmlString ActionLinkForQueueCount <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, long queueLkup, long discCat)
        {
            StringBuilder output = new StringBuilder();
            long          count  = (long)ModelMetadata.FromLambdaExpression(expression, helper.ViewData).Model;
            QueueSummary  Model  = helper.ViewData.Model as QueueSummary;

            if (Model.lstUserAccessQueueLkups != null && Model.lstUserAccessQueueLkups.Contains(queueLkup) && count != 0)
            {
                HtmlString anchorTag;
                if (discCat == (long)DiscripancyCategory.OOA || discCat == (long)DiscripancyCategory.SCC || discCat == (long)DiscripancyCategory.TRR)
                {
                    anchorTag = LinkExtensions.ActionLink(helper, count.ToString(), "SearchFromHome", "Common", new { @ComplianceStartDate = Model.StartDate, @ComplianceEndDate = Model.EndDate, @Queue = queueLkup, @data = discCat }, new { @class = "count-button", @Title = "View Queue" });
                }
                else
                {
                    anchorTag = LinkExtensions.ActionLink(helper, count.ToString(), "SearchFromHome", "Common", new { @CaseCreationStartDate = Model.StartDate, @CaseCreationEndDate = Model.EndDate, @Queue = queueLkup, @data = discCat }, new { @class = "count-button", @Title = "View Queue" });
                }
                output.Append(anchorTag);
            }
            else
            {
                output.Append(string.Format(count.ToString()));
            }
            return(new MvcHtmlString(output.ToString()));
        }
Exemple #3
0
        public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName,
                                             string controllerName, object routeValues)
        {
            var actionLink = LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName, routeValues, null);

            if (actionLink == MvcHtmlString.Empty)
            {
                return(MvcHtmlString.Empty);
            }

            var currentAction     = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

            var builder = new TagBuilder("li")
            {
                InnerHtml = actionLink.ToHtmlString()
            };

            if (controllerName.ToLower() == currentController.ToLower())
            {
                builder.AddCssClass("active");
            }

            return(new MvcHtmlString(builder.ToString()));
        }
        public static MvcHtmlString ActionlinkWithSpanForIcon(this HtmlHelper htmlHelper, string actionName, object routeValues, object htmlAttributes, string spanAttributes)
        {
            string strActionLink = LinkExtensions.ActionLink(htmlHelper, "null", actionName, routeValues, htmlAttributes).ToString();

            strActionLink = strActionLink.Replace("null", string.Format("<span class='{0}'></span>", spanAttributes));

            return(MvcHtmlString.Create(strActionLink));
        }
        public static MvcHtmlString CultureActionLink(this HtmlHelper htmlHelper, String langName)
        {
            var culture     = CultureInfo.CreateSpecificCulture(langName);
            var displayName = culture.Name.StartsWith("en")
                ? culture.NativeName
                : culture.EnglishName + " - " + culture.NativeName;

            return(LinkExtensions.ActionLink(htmlHelper, displayName, "Language", "Home", new { Lang = culture.Name }, null));
        }
Exemple #6
0
        /// <summary>
        /// se o usuário logado tem acesso ao recurso, gera um item de menu usando um list item html. Retorna string vazia caso contrário.
        /// </summary>
        /// <param name="html">HtmlHelper - o html helper do Razor</param>
        /// <param name="texto">string - o texto do menu</param>
        /// <param name="acao">string - a ação a ser verificada</param>
        /// <param name="controller">string - o controller a ser verificado</param>
        /// <returns>HtmlString - Um item de menu em html</returns>
        public static HtmlString MenuItemLiSeguro(this HtmlHelper html, string texto, string acao, string controller)
        {
            if (ControleAcesso.TemAcesso(controller, acao))
            {
                return(new HtmlString(string.Format("<li>{0}</li>", LinkExtensions.ActionLink(html, texto, acao, controller))));
            }

            return(new HtmlString(""));
        }
        /// <summary>
        /// Creates the links of the references.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper">The html helper</param>
        /// <param name="referencies">The referencies contained IDs and labels</param>
        /// <param name="action">The action name</param>
        /// <param name="controller">The controller name</param>
        /// <param name="htmlAttributes">The html attributes</param>
        /// <returns>Returns the created links of the references</returns>
        public static string CreateLinks <T>(this HtmlHelper <T> htmlHelper, ReferenceString referenceString, string action, string controller, object htmlAttributes)
        {
            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair <Guid, string> reference in referenceString.GetReferencies())
            {
                sb.Append(LinkExtensions.ActionLink(htmlHelper, reference.Value, action, controller, new { id = reference.Key, name = UrlUtils.ToSeoUrl(reference.Value) }, htmlAttributes).ToString());
            }
            return(sb.ToString());
        }
Exemple #8
0
        public static MvcHtmlString MenuLinkLi(this HtmlHelper htmlHelper, string linkText, string action, string controller, string userName)
        {
            ////UsuarioTO usuarioTO = Cache.DiccionarioUsuariosLogueados[usuario];
            //string areaName = (htmlHelper.ViewContext.RouteData.DataTokens["area"] != null && string.IsNullOrEmpty((string)htmlHelper.ViewContext.RouteData.DataTokens["area"])) ? string.Empty : (string)htmlHelper.ViewContext.RouteData.DataTokens["area"];
            ////string controllerName = (string)html.ViewContext.RouteData.GetRequiredString("controller");
            ////string actionName = (string)html.ViewContext.RouteData.DataTokens["action"];

            ///*if(Cache.DiccionarioUsuariosLogueados.ContainsKey(userName) && Cache.DiccionarioUsuariosLogueados[userName].havePermissions(areaName, controller, action)) {
            //*/

            //    var result = new StringBuilder();
            //    //LinkExtensions.ActionLink(htmlHelper, linkText, action, controller);
            //    //var url = UrlHelper.GenerateContentUrl("/" + controller + "/" + action, html.ViewContext.HttpContext);
            //    result.Append("<li>");
            //   // result.Append("<a href=\"");
            //    //result.Append(HttpUtility.HtmlAttributeEncode(url));
            //    //result.Append("\" data-ajax-update=\"");
            //    //result.Append("\" >" + linkString + "</a>");
            //    result.Append(LinkExtensions.ActionLink(htmlHelper, linkText, action, controller).ToString());
            //    result.Append("</li>");
            //    //result.Append(HttpUtility.HtmlAttributeEncode("#" + ajaxUpdateId));
            //    // ... and so on
            //   // <li>@Html.ActionLink(@Resources.Resources.administracion_menu_roles, "Index", "Roles")</li>

            //    return new MvcHtmlString(result.ToString());
            ///*}*/
            ////return new MvcHtmlString("");

            //UsuarioTO usuarioTO = Cache.DiccionarioUsuariosLogueados[usuario];
            string areaName = (htmlHelper.ViewContext.RouteData.DataTokens["area"] != null && string.IsNullOrEmpty((string)htmlHelper.ViewContext.RouteData.DataTokens["area"])) ? string.Empty : (string)htmlHelper.ViewContext.RouteData.DataTokens["area"];

            //string controllerName = (string)html.ViewContext.RouteData.GetRequiredString("controller");
            //string actionName = (string)html.ViewContext.RouteData.DataTokens["action"];

            if (Cache.DiccionarioUsuariosLogueados.ContainsKey(userName) && Cache.DiccionarioUsuariosLogueados[userName].havePermissions(areaName, controller, action))
            {
                var result = new StringBuilder();
                //LinkExtensions.ActionLink(htmlHelper, linkText, action, controller);
                //var url = UrlHelper.GenerateContentUrl("/" + controller + "/" + action, html.ViewContext.HttpContext);
                result.Append("<li>");
                // result.Append("<a href=\"");
                //result.Append(HttpUtility.HtmlAttributeEncode(url));
                //result.Append("\" data-ajax-update=\"");
                //result.Append("\" >" + linkString + "</a>");
                result.Append(LinkExtensions.ActionLink(htmlHelper, linkText, action, controller).ToString());
                result.Append("</li>");
                //result.Append(HttpUtility.HtmlAttributeEncode("#" + ajaxUpdateId));
                // ... and so on
                // <li>@Html.ActionLink(@Resources.Resources.administracion_menu_roles, "Index", "Roles")</li>

                return(new MvcHtmlString(result.ToString()));
            }
            return(new MvcHtmlString(""));
        }
Exemple #9
0
        public static MvcHtmlString LocalizedActionLink <T>(this HtmlHelper <T> htmlHelper, string resourceKey, string action = "#", string controller = "", object routeValues = null, object htmlAttributes = null)
        {
            string tempName = Guid.NewGuid().ToString();

            if (routeValues == null && action != "Index" && action != "#")
            {
                action += "/";
            }
            string actionLinkMvcHtmlString = LinkExtensions.ActionLink(htmlHelper, tempName, action, controller, routeValues, htmlAttributes).ToHtmlString();

            actionLinkMvcHtmlString = actionLinkMvcHtmlString.Replace(tempName, ResourceUtils.GetString(resourceKey));
            return(MvcHtmlString.Create(actionLinkMvcHtmlString));
        }
Exemple #10
0
        public static MvcHtmlString ListGroupLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues)
        {
            var currentAction     = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

            if (actionName.ToLower() == currentAction.ToLower())
            {
                return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, currentController, routeValues, new { @class = "list-group-item active" }));
            }
            else
            {
                return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, currentController, routeValues, new { @class = "list-group-item" }));
            }
        }
Exemple #11
0
 public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName = null, string protocol = null, string hostName = null, string fragment = null, object routeValues = null, string accessKey = null, string charset = null, string coords = null, string cssClass = null, string dir = null, string hrefLang = null, string id = null, string lang = null, string name = null, string rel = null, string rev = null, string shape = null, string style = null, string target = null, string title = null)
 {
     return(LinkExtensions.ActionLink(
                htmlHelper,
                linkText,
                actionName,
                controllerName,
                protocol,
                hostName,
                fragment,
                routeValues as RouteValueDictionary ?? new RouteValueDictionary(routeValues),
                AnchorAttributes(accessKey, charset, coords, cssClass, dir, hrefLang, id, lang, name, rel, rev, shape, style, target, title)
                ));
 }
Exemple #12
0
 /// <summary>
 /// Checks user security permissions.  If allowed, displays link. Otherwise, displays nothing.
 /// </summary>
 /// <returns>Link or empty string.</returns>
 public static MvcHtmlString AuthorizedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, IDictionary <string, object> htmlAttributes)
 {
     // See if user has access to the action.
     if (ActionIsAccessibleToUser(htmlHelper: htmlHelper, actionName: actionName, controllerName: controllerName, routeValues: routeValues))
     {
         // User has access. Generate ActionLink.
         return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName, protocol, hostName, fragment, routeValues, htmlAttributes));
     }
     else
     {
         // User does not have access. Return empty string.
         return(MvcHtmlString.Empty);
     }
 }
Exemple #13
0
        /// <summary>
        /// Creates the localized link for open the dialog.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper">The html helper</param>
        /// <param name="resourceKey">The resource key to be localized</param>
        /// <param name="targetDialog">The html id of the dialog to be opened</param>
        /// <param name="action">The action to execute</param>
        /// <param name="controller">The controller of the action</param>
        /// <param name="routeValues">The route values for the action</param>
        /// <param name="htmlAttributes">The additional html attributes for the link</param>
        /// <returns></returns>
        public static MvcHtmlString DialogActionLink <T>(this HtmlHelper <T> htmlHelper, string resourceKey, string targetDialog, string action, string controller, object routeValues = null, object htmlAttributes = null)
        {
            string tempName = Guid.NewGuid().ToString();
            RouteValueDictionary attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

            attributes.Add("data-toggle", "modal");
            attributes.Add("data-target", targetDialog);
            attributes.Add("data-placement", "top");
            attributes["class"] += " show-dialog tooltips";
            if (attributes.ContainsKey("title"))
            {
                attributes["title"] = ResourceUtils.GetString(attributes["title"].ToString());
            }
            return(MvcHtmlString.Create(LinkExtensions.ActionLink(htmlHelper, tempName, action, controller, HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues), attributes).ToHtmlString().Replace(tempName, ResourceUtils.GetString(resourceKey))));
        }
Exemple #14
0
        public override string GenerateUrl(string pathTemplate, string[] parameters, NDjango.Interfaces.IContext context)
        {
            var htmlHelperOption = context.tryfind("Html");

            if (htmlHelperOption == null)
            {
                return("");
            }

            var htmlHelper = (HtmlHelper)htmlHelperOption.Value;
            var anchor     = LinkExtensions.ActionLink(htmlHelper, pathTemplate, pathTemplate, parameters[0]).ToHtmlString();

            //retriving relativePath from anchor element.
            var startindex = anchor.IndexOf("href") + 6; var endIndex = anchor.IndexOf("\"", startindex);

            return(anchor.Substring(startindex, endIndex - startindex));
        }
Exemple #15
0
        public static MvcHtmlString UserInfo(this HtmlHelper htmlHelper)
        {
            string res = "<div style=\"position: absolute; right: 10px; top: 10px;\" >";

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                res += $"<div>Zalogowano jako: {HttpContext.Current.User.Identity.Name}</div>";
                res += "<div>" + LinkExtensions.ActionLink(htmlHelper, "Wyloguj", "Logout", "Account") + "</div>";
            }

            else
            {
                res += "<div>" + LinkExtensions.ActionLink(htmlHelper, "Zaloguj", "Login", "Account") + "</div>";
            }

            res += "</div>";

            return(MvcHtmlString.Create(res));
        }
Exemple #16
0
        /// <summary>
        /// Gets the breadcrumb for the current location.
        /// </summary>
        /// <param name="html">A HtmlHelper that is the current HTML helper.</param>
        /// <param name="separator">A MvcHtmlString containing the separator to use between the breadcrumbs.</param>
        /// <param name="homeController">A string containing the name of the homepage controller.</param>
        /// <param name="indexAction">A string containing the name of the index action.</param>
        /// <returns>A MvcHtmlString containing the breadcrumb.</returns>
        public static MvcHtmlString GetBreadcrumb(this HtmlHelper html, MvcHtmlString separator, string homeController = "Home", string indexAction = "Index")
        {
            MvcHtmlString ReturnValue;

            if (html.GetControllerName(out string ControllerName) && html.GetActionName(out string ActionName))
            {
                if (ControllerName != homeController)
                {
                    string ModelName;

                    ModelName = html.GetModelDisplayName();
                    if (ModelName == null)
                    {
                        ModelName = ControllerName;
                    }

                    ReturnValue = LinkExtensions.ActionLink(html, homeController, indexAction, homeController);
                    ReturnValue = ReturnValue.Concat(separator);
                    if (ActionName != indexAction)
                    {
                        string ActionDisplayName;

                        ActionDisplayName = html.GetActionDisplayName();
                        if (ActionDisplayName == null)
                        {
                            ActionDisplayName = ActionName;
                        }

                        ReturnValue = ReturnValue.Concat(LinkExtensions.ActionLink(html, ModelName, indexAction, html.ViewContext.RouteData.Values["controller"].ToString()));
                        ReturnValue = ReturnValue.Concat(separator);
                        ReturnValue = ReturnValue.Concat(ActionDisplayName);
                    }
                    else
                    {
                        ReturnValue = ReturnValue.Concat(ModelName);
                    }
                }
                else
                {
                    ReturnValue = new MvcHtmlString(homeController);
                }
            }
        private static MvcHtmlString WriteMenuLink(HtmlHelper html, string text, string action, string controller, string area, object routeValues = null, params string[] cssClasses)
        {
            RouteValueDictionary        allRouteValues    = new RouteValueDictionary(routeValues);
            Dictionary <string, object> allHtmlAttributes = new Dictionary <string, object>();
            MvcHtmlString link = null;

            if (area != null)
            {
                allRouteValues["area"] = area;
            }

            if (!cssClasses.IsNullOrEmpty())
            {
                allHtmlAttributes["class"] = string.Join(" ", cssClasses);
            }

            link = LinkExtensions.ActionLink(html, text, action, controller, routeValues: allRouteValues, htmlAttributes: allHtmlAttributes);

            return(link);
        }
Exemple #18
0
        public static IHtmlString EndingFormButtons(this HtmlHelper html, string submitButtonText = "Save", string anchorValue = "Go Back", string anchorAction = "GoBack", string anchorController = "Home")
        {
            TagBuilder div = new TagBuilder("div");

            div.AddCssClass("input-group mb-3 my-3 d-flex justify-content-around");

            MvcHtmlString anchor = LinkExtensions.ActionLink(html, anchorValue, anchorAction, anchorController, new { area = "" }, new { @class = "btn btn-secondary btn-lg" });

            TagBuilder submit = new TagBuilder("input");

            submit.AddCssClass("btn btn-success btn-lg");
            submit.MergeAttribute("type", "submit");
            submit.MergeAttribute("value", submitButtonText);

            StringBuilder htmlBuilder = new StringBuilder();

            htmlBuilder.Append(anchor.ToHtmlString());
            htmlBuilder.Append(submit.ToString(TagRenderMode.SelfClosing));

            div.InnerHtml = htmlBuilder.ToString();
            return(MvcHtmlString.Create(div.ToString(TagRenderMode.Normal)));
        }
Exemple #19
0
        public static MvcHtmlString Pagination(this HtmlHelper helper, int currnetPage, int allPages, string actionName, string controllerName, string pageVarName)
        {
            TagBuilder nav = new TagBuilder("nav");
            TagBuilder ul  = new TagBuilder("ul");

            ul.MergeAttribute("class", "pagination");
            TagBuilder li = new TagBuilder("li");

            if (currnetPage == 1)
            {
                li.AddCssClass("disabled");
            }

            li.InnerHtml = LinkExtensions.ActionLink(helper, "<<", actionName, controllerName, new { id = currnetPage - 1 }, htmlAttributes: null).ToString();
            ul.InnerHtml = li.ToString();
            for (int i = 1; i <= allPages; i++)
            {
                li = new TagBuilder("li");
                if (i == currnetPage)
                {
                    li.AddCssClass("active");
                }

                li.InnerHtml  = LinkExtensions.ActionLink(helper, i.ToString(), actionName, controllerName, new { id = i }, htmlAttributes: null).ToString();
                ul.InnerHtml += li.ToString();
            }

            li = new TagBuilder("li");
            if (currnetPage == allPages)
            {
                li.AddCssClass("disabled");
            }

            li.InnerHtml  = LinkExtensions.ActionLink(helper, ">>", actionName, controllerName, new { id = currnetPage + 1 }, htmlAttributes: null).ToString();
            ul.InnerHtml += li.ToString();
            nav.InnerHtml = ul.ToString();
            return(new MvcHtmlString(nav.ToString()));
        }
        /// <summary>
        /// Returns the table row Edit | Details | Delete links which the user in scope has permission to.
        /// </summary>
        /// <param name="html"></param>
        /// <param name="linkId"></param>
        /// <returns></returns>
        public static MvcHtmlString IndexLinks(this HtmlHelper html, object linkId)
        {
            // Get the users role
            EnumHelper.Roles role = EnumHelper.Roles.Viewer;
            if (HttpContext.Current.User.IsInRole(EnumHelper.Roles.Author.ToString()))
            {
                role = EnumHelper.Roles.Author;
            }
            else if (HttpContext.Current.User.IsInRole(EnumHelper.Roles.Admin.ToString()))
            {
                role = EnumHelper.Roles.Admin;
            }

            // Get the current route Controller name
            var    currentRouteData = html.ViewContext.RouteData;
            string controller       = currentRouteData.GetRequiredString("controller");

            // Check user permissions
            CustomApplicationDbContext  context          = new CustomApplicationDbContext();
            IQueryable <RolePermission> rolePermissions  = context.RolePermissions;
            PermissionHelper            permissionHelper = new PermissionHelper(rolePermissions);

            // Build the MvcHtmlString
            StringBuilder linkStringBuilder = new StringBuilder();

            if (permissionHelper.HasPermission(role, controller, "Edit"))
            {
                linkStringBuilder.Append(string.Format("{0} |",
                                                       LinkExtensions.ActionLink(html, "Edit", "Edit", linkId)));
            }
            linkStringBuilder.Append(LinkExtensions.ActionLink(html, "Details", "Details", linkId));
            if (permissionHelper.HasPermission(role, controller, "Delete"))
            {
                linkStringBuilder.Append(string.Format("| {0}",
                                                       LinkExtensions.ActionLink(html, "Delete", "Delete", linkId)));
            }
            return(new MvcHtmlString(linkStringBuilder.ToString()));
        }
Exemple #21
0
        public static MvcHtmlString HeaderActionLinkLi(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
        {
            var link = ((string)htmlHelper.ViewContext.RouteData.Values["controller"] == controllerName && (string)htmlHelper.ViewContext.RouteData.Values["action"] == actionName) ? " class=\"" + ACTIVE_CLASS + "\"" : null;

            return(new MvcHtmlString("<li" + (link != null ? link : "") + ">" + LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName) + "</li>"));
        }
 public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, String linkText, String actionName, String controllerName, RouteValueDictionary routeValues, object htmlAttributes)
 {
     return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, controllerName, routeValues, htmlAttributes.CastToDictionary()));
 }
        public static string Pager <T>(this HtmlHelper html, PagedList <T> data)
        {
            //数字导航的开始数字
            int start = (data.PageIndex - 5) >= 1 ? (data.PageIndex - 5) : 1;
            //数字导航的结束数字
            int end = (data.TotalPages - start) > 10 ? start + 10 : data.TotalPages;

            //路由数据
            RouteValueDictionary vs = html.ViewContext.RouteData.Values;
            //URL数据
            var queryString = html.ViewContext.HttpContext.Request.QueryString;

            //合并URL数据
            foreach (string key in queryString.Keys)
            {
                if (queryString[key] != null && !string.IsNullOrEmpty(key))
                {
                    vs[key] = queryString[key];
                }
            }
            //合并表单数据
            var FormString = html.ViewContext.HttpContext.Request.Form;

            foreach (string key in FormString.Keys)
            {
                vs[key] = FormString[key];
            }
            //输出分页Html
            var builder = new StringBuilder();

            builder.AppendFormat("<div class=\"mvc_pager\">");
            //显示首页和上页
            if (data.HasPreviousPage)
            {
                vs["pageIndex"] = 1;
                builder.Append(LinkExtensions.ActionLink(html, "首页", vs["action"].ToString(), vs));
                vs["pageIndex"] = data.PageIndex - 1;
                builder.Append(LinkExtensions.ActionLink(html, "上页", vs["action"].ToString(), vs));
            }
            //显示数字页码
            for (int i = start; i <= end; i++)
            {
                vs["pageIndex"] = i;
                if (i == data.PageIndex)
                {
                    builder.Append("<font class='thispagethis'>" + i.ToString() + "</font>");
                }
                else
                {
                    builder.Append(LinkExtensions.ActionLink(html, i.ToString(), vs["action"].ToString(), vs));
                }
            }
            //显示下页和末页
            if (data.HasNextPage)
            {
                vs["pageIndex"] = data.PageIndex + 1;
                builder.Append(LinkExtensions.ActionLink(html, "下页", vs["action"].ToString(), vs));
                vs["pageIndex"] = data.TotalPages;
                builder.Append(LinkExtensions.ActionLink(html, "末页", vs["action"].ToString(), vs));
            }
            builder.Append("共" + data.TotalCount + "条 第" + data.PageIndex + "页/共" + data.TotalPages + "页 </div>");
            return(builder.ToString());
        }
 public IHtmlString ActionLink(string title, string actionName, string controllerName)
 {
     return(LinkExtensions.ActionLink(this, title, actionName, controllerName));
 }
Exemple #25
0
        public static MvcHtmlString Grid <T>(this HtmlHelper html, IEnumerable <T> items, string defaultSort, string gridCaption, bool canPage = false, int rowPerPage = 50, int rowCount = 0, int activePage = 1, string idGrid = "grid", bool isWindowMode = false, List <KeyValuePair <string, object> > parameters = null)
        {
            StringBuilder output = new StringBuilder();

            if (items.Count() > 0)
            {
                List <GridColumnOrder> columns = new List <GridColumnOrder>();
                if (parameters == null)
                {
                    parameters = new List <KeyValuePair <string, object> >();
                }

                parameters.Add(new KeyValuePair <string, object>("windowMode", isWindowMode));
                if (rowCount == 0)
                {
                    rowCount = items.Count();
                }

                if (canPage)
                {
                    output.AppendLine(CreatePageNavigator(html, rowPerPage, rowCount, activePage: activePage, parameters: parameters).ToHtmlString());
                }

                var grid = new WebGrid((IEnumerable <dynamic>)items, canPage: false, canSort: false, rowsPerPage: rowPerPage, defaultSort: defaultSort);
                foreach (var property in typeof(T).GetProperties())
                {
                    bool showColumn = true;
                    var  attributes = (property.GetCustomAttributes(typeof(GridConfigAttribute), false));
                    if (attributes != null)
                    {
                        foreach (var attribute in attributes)
                        {
                            string propertyName = property.Name;
                            var    attr         = (GridConfigAttribute)attribute;
                            string style        = attr.Style;

                            showColumn = !attr.Hidden;
                            if (showColumn)
                            {
                                showColumn = !(isWindowMode && attr.HiddenOnWindowMode);
                            }

                            if (showColumn)
                            {
                                showColumn = attr.Index > 0;
                            }

                            if (attr.CreateCheckBox && !isWindowMode)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    Format = (dynamic item) =>
                                    {
                                        var entity      = (T)(((WebGridRow)item).Value);
                                        var objectValue = entity.GetType().GetProperty(propertyName).GetValue(entity, null);
                                        return(InputExtensions.CheckBox(html, String.Format("chk{0}", propertyName), new { @class = "checkable", value = objectValue }));
                                    },
                                    Style = style
                                }));
                            }

                            if (attr.CreateImage && !isWindowMode)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    //Header = SpongeSolutions.ServicoDireto.Internationalization.Label.ResourceManager.GetString(propertyName),
                                    Format = (dynamic item) =>
                                    {
                                        var entity      = (T)(((WebGridRow)item).Value);
                                        var objectValue = entity.GetType().GetProperty(propertyName).GetValue(entity, null);
                                        objectValue     = String.Concat(SpongeSolutions.ServicoDireto.Admin.SiteContext.LayoutPath, objectValue);
                                        return(new MvcHtmlString(String.Format("<img src='{0}'/>", objectValue)));
                                    },
                                    Style = style
                                }));
                            }

                            if (attr.CreateEditLink)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    Format = (item) =>
                                    {
                                        var entity = (T)(((WebGridRow)item).Value);
                                        try
                                        {
                                            string objectValue       = entity.GetType().GetProperty(propertyName).GetValue(entity, null).ToString();
                                            string objectDescription = null;

                                            if (attr.RelatedFieldName != null && attr.RelatedFieldName.Count() > 0)
                                            {
                                                foreach (var fieldName in attr.RelatedFieldName)
                                                {
                                                    objectDescription += String.Format("{0}-", entity.GetType().GetProperty(fieldName).GetValue(entity, null));
                                                }

                                                objectDescription = objectDescription.Remove(objectDescription.Length - 1, 1);
                                            }
                                            if (objectDescription == null)
                                            {
                                                objectDescription = objectValue;
                                            }

                                            if (isWindowMode)
                                            {
                                                return(new HtmlString(String.Format("<a href=\"javascript:AddSelected('{0}','{1}')\">{2}</a>", objectValue, objectDescription, SpongeSolutions.ServicoDireto.Internationalization.Label.Select)));
                                            }
                                            else
                                            {
                                                return(LinkExtensions.ActionLink(html, SpongeSolutions.ServicoDireto.Internationalization.Label.Edit, "create", new { id = objectValue }));
                                            }
                                        }
                                        catch (Exception)
                                        {
                                            return(string.Empty);
                                        }
                                    },
                                    Style = style
                                }));
                            }

                            if (attr.EnumType != null)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    Style      = style,
                                    ColumnName = property.Name,
                                    Header     = SpongeSolutions.ServicoDireto.Internationalization.Label.ResourceManager.GetString(property.Name),
                                    Format     = (item) =>
                                    {
                                        var entity      = (T)(((WebGridRow)item).Value);
                                        var objectValue = entity.GetType().GetProperty(propertyName).GetValue(entity, null);
                                        //var enumSource = Activator.CreateInstance(attr.EnumType);
                                        //TODO: COLOCAR DE MODO DINAMICO
                                        return(SpongeSolutions.Core.Translation.EnumTranslator.Translate <Enums.StatusType>(SpongeSolutions.Core.Helpers.EnumHelper.TryParse <Enums.StatusType>(objectValue)).DisplayName);
                                    }
                                }));
                                showColumn = false;
                            }

                            if (showColumn)
                            {
                                columns.Add(new GridColumnOrder(attr.Index, new WebGridColumn()
                                {
                                    ColumnName = property.Name,
                                    Header     = SpongeSolutions.ServicoDireto.Internationalization.Label.ResourceManager.GetString(property.Name)
                                    ,
                                    Style = style
                                }));
                            }
                        }
                    }
                }

                output.AppendLine(MvcHtmlString.Create(grid.GetHtml(
                                                           tableStyle: "grid",
                                                           caption: gridCaption,
                                                           alternatingRowStyle: "alternating",
                                                           htmlAttributes: new { id = idGrid },
                                                           columns: columns.OrderBy(p => p.Index).Select(p => p.Column).ToArray()).ToHtmlString()).ToHtmlString());

                if (canPage)
                {
                    output.AppendLine(CreatePageNavigator(html, rowPerPage, rowCount, activePage: activePage, parameters: parameters).ToHtmlString());
                }
            }
            else
            {
                var container = new TagBuilder("div");
                container.AddCssClass("notice");
                container.SetInnerText(Internationalization.Label.Records_Not_Found);
                output.Append(container.ToString());
            }
            return(MvcHtmlString.Create(output.ToString()));
        }
Exemple #26
0
 /// <summary>
 /// 返回一个链接
 /// </summary>
 /// <param name="htmlHelper"></param>
 /// <param name="linkText">链接文字</param>
 /// <param name="actionName">动作名</param>
 /// <param name="controllerName">控制器名</param>
 /// <param name="areaName">区域名</param>
 /// <param name="htmlAttributes">html特性</param>
 public static MvcHtmlString AsiatekActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string areaName, object htmlAttributes)
 {
     return(LinkExtensions.ActionLink(htmlHelper, linkText, actionName, new { controller = controllerName, area = areaName }, htmlAttributes));
 }
Exemple #27
0
        public static IHtmlString PacienteCuadros(this HtmlHelper <IPagedList <PacienteViewModel> > htmlHelper, IEnumerable <PacienteViewModel> model)
        {
            var macroDiv = new TagBuilder("div");

            macroDiv.AddCssClass("card-columns");
            var macroBuilder = new StringBuilder();
            var urlHelper    = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            foreach (var item in model)
            {
                var outerDiv   = new TagBuilder("div");
                var cardBody   = new TagBuilder("div");
                var cardUL     = new TagBuilder("ul");
                var cardFooter = new TagBuilder("div");
                outerDiv.AddCssClass("card border-info mb-3");
                cardBody.AddCssClass("card-body");
                cardUL.AddCssClass("list-group list-group-flush");
                cardFooter.AddCssClass("card-footer");

                //--Card Body
                var nombreH = new TagBuilder("h5");
                nombreH.AddCssClass("card-title");
                nombreH.InnerHtml = DisplayExtensions.DisplayFor(htmlHelper, m => item.FullName).ToHtmlString();
                var subRaza = new TagBuilder("h6");
                subRaza.AddCssClass("card-subtitle mb-2 text-muted");
                subRaza.InnerHtml = $"Raza : {DisplayExtensions.DisplayFor(htmlHelper, m => item.Raza.Nombre).ToHtmlString()}";
                var subChip = new TagBuilder("h6");
                subChip.AddCssClass("card-subtitle mb-2 text-muted");
                StringBuilder subChipText = new StringBuilder();
                subChipText.Append(DisplayNameExtensions.DisplayNameFor(htmlHelper, m => m.First().Microchip_Licencia).ToHtmlString());
                subChipText.Append(" : ");
                subChipText.Append(DisplayExtensions.DisplayFor(htmlHelper, m => item.Microchip_Licencia).ToHtmlString());
                subChip.InnerHtml = subChipText.ToString();
                var pTag = new TagBuilder("p");
                pTag.AddCssClass("card-text");
                pTag.InnerHtml = $"Fecha Registro : {item.FechaIngreso.ToShortDateString()}";
                StringBuilder bodyText = new StringBuilder();
                bodyText.Append(nombreH.ToString(TagRenderMode.Normal));
                bodyText.Append(subRaza.ToString(TagRenderMode.Normal));
                bodyText.Append(subChip.ToString(TagRenderMode.Normal));
                bodyText.Append(pTag.ToString(TagRenderMode.Normal));
                cardBody.InnerHtml = bodyText.ToString();
                //------

                //--Card UL
                var liEdad   = new TagBuilder("li");
                var liColor  = new TagBuilder("li");
                var liGenero = new TagBuilder("li");
                liEdad.AddCssClass("list-group-item");
                liColor.AddCssClass("list-group-item");
                liGenero.AddCssClass("list-group-item");

                var message = $"Edad : {item.Edad}";
                liEdad.InnerHtml = message;
                var colorText = new StringBuilder();
                colorText.Append(DisplayNameExtensions.DisplayNameFor(htmlHelper, m => m.First().Color).ToHtmlString());
                colorText.Append(" : ");
                colorText.Append(DisplayExtensions.DisplayFor(htmlHelper, m => item.Color).ToHtmlString());
                liColor.InnerHtml = colorText.ToString();
                var generoText = new StringBuilder();
                generoText.Append(DisplayNameExtensions.DisplayNameFor(htmlHelper, m => m.First().Genero).ToHtmlString());
                generoText.Append(" : ");
                generoText.Append(DisplayExtensions.DisplayFor(htmlHelper, m => item.Genero).ToHtmlString());
                liGenero.InnerHtml = generoText.ToString();

                var cardUlText = new StringBuilder();
                cardUlText.Append(liEdad.ToString(TagRenderMode.Normal));
                cardUlText.Append(liColor.ToString(TagRenderMode.Normal));
                cardUlText.Append(liGenero.ToString(TagRenderMode.Normal));
                cardUL.InnerHtml = cardUlText.ToString();
                //------

                //--Card Footer

                var editarBtn = new TagBuilder("a");
                editarBtn.AddCssClass("card-link-btn");
                editarBtn.MergeAttribute("title", "Editar Datos Paciente");
                editarBtn.MergeAttribute("href", $"{urlHelper.Action("Editar", new { id = item.ID })}");
                editarBtn.InnerHtml = " <i class='fas fa-edit'></i> ";
                var deleteBtn = new TagBuilder("span");
                deleteBtn.AddCssClass("card-link-btn notDisplay");
                deleteBtn.MergeAttribute("onclick", $"DeleteThis({item.ID})");
                deleteBtn.InnerHtml = "Eliminar";
                var linkVer    = LinkExtensions.ActionLink(htmlHelper, "Ver Lista de Chequeos", "HistoricoPaciente", "Chequeos", new { id = item.ID }, htmlAttributes: new { @class = "card-link" });
                var linkPro    = LinkExtensions.ActionLink(htmlHelper, "Ver Propietario(s)", "VerPropietarios", new { id = item.ID }, htmlAttributes: new { @class = "card-link" });
                var nuevoCheck = LinkExtensions.ActionLink(htmlHelper, "Nuevo Chequeo", "Nuevo", "Chequeo", new { id = item.ID }, htmlAttributes: new { @class = "card-link" });
                var footerText = new StringBuilder();

                footerText.Append(editarBtn.ToString(TagRenderMode.Normal));
                footerText.Append(" | ");
                footerText.Append(linkVer.ToHtmlString());
                footerText.Append(" | ");
                footerText.Append(deleteBtn.ToString(TagRenderMode.Normal));
                footerText.Append("  ");
                footerText.Append(linkPro.ToHtmlString());
                footerText.Append(" | ");
                footerText.Append(nuevoCheck.ToHtmlString());

                cardFooter.InnerHtml = footerText.ToString();
                //------

                //Renderizando Outer BODY
                StringBuilder htmlBuilder = new StringBuilder();
                htmlBuilder.Append(cardBody.ToString(TagRenderMode.Normal));
                htmlBuilder.Append(cardUL.ToString(TagRenderMode.Normal));
                htmlBuilder.Append(cardFooter.ToString(TagRenderMode.Normal));
                outerDiv.InnerHtml = htmlBuilder.ToString();

                macroBuilder.Append(outerDiv.ToString(TagRenderMode.Normal));
            }
            macroDiv.InnerHtml = macroBuilder.ToString();
            var html = macroDiv.ToString(TagRenderMode.Normal);

            return(MvcHtmlString.Create(html));
        }
Exemple #28
0
        /// <summary>
        /// Creates link similar to Html.ActionLink, just correctly sets the sortDir and sortCol parameters and CSS classes
        /// </summary>
        /// <param name="html">Extension instance</param>
        /// <param name="linkText">Text to display as the link</param>
        /// <param name="actionName">Action name as in Html.ActionLink</param>
        /// <param name="controllerName">Controller name as in Html.ActionLink</param>
        /// <param name="routeDictionary">RouteDictionary same as in Html.ActionLink</param>
        /// <param name="htmlAttributes">HtmlAttributes dictionary same as in Html.ActionLink</param>
        /// <param name="sortColumn">What sortcol id will this column stand for</param>
        /// <returns>Formatted and styled link</returns>
        public static MvcHtmlString SortableHeaderActionLink(this HtmlHelper html, string linkText, string actionName, string controllerName, object routeDictionary, IDictionary <string, object> htmlAttributes, int sortColumn)
        {
            int querySortDir;

            if (!int.TryParse(((html.ViewBag.sortDir ?? html.ViewContext.HttpContext.Request.QueryString["sortDir"]) ?? "").ToString(), out querySortDir))
            {
                querySortDir = (int)SortDirection.Asc;
            }

            int oppositeQuerySortDir = querySortDir == (int)SortDirection.Asc ? (int)SortDirection.Desc : (int)SortDirection.Asc;

            int querySortCol;

            if (!int.TryParse(((html.ViewBag.sortCol ?? html.ViewContext.HttpContext.Request.QueryString["sortCol"]) ?? "").ToString(), out querySortCol))
            {
                querySortCol = 0;
            }

            RouteValueDictionary newRouteDictionary = new RouteValueDictionary(routeDictionary ?? new { });

            // for "key with multiple values" ends up like "&xxx=x&xxx=xx" in the url, the above code can not translate it into
            // newRouteDictionary.Add("xxx", x);
            // newRouteDictionary.Add("xxx", xx);
            // the key can not be duplicated we will need to do some work around
            // The below code translate it into
            // newRouteDictionary.Add("xxx[0]", x);
            // newRouteDictionary.Add("xxx[1]", xx);
            // it will be like "&xxx[0]=x&xxx[1]=xx" in the query string, this is accepted by the controller action as array as well
            // reference http://stackoverflow.com/questions/27383705/how-to-build-a-routevaluedictionary-when-a-route-has-multiple-values
            List <KeyValuePair <string, object> > multiValueRoutes = newRouteDictionary.Where(x => x.Value != null && x.Value.GetType().IsArray).ToList();

            if (multiValueRoutes.Count() > 0)
            {
                foreach (KeyValuePair <string, object> multiValueRoute in multiValueRoutes)
                {
                    if (multiValueRoute.Value is int[])
                    {
                        int[] values = (int[])multiValueRoute.Value;
                        for (int i = 0; i < values.Length; i++)
                        {
                            newRouteDictionary.Add(multiValueRoute.Key + "[" + i + "]", values[i]);
                        }
                        newRouteDictionary.Remove(multiValueRoute.Key);
                    }
                    else if (multiValueRoute.Value is string[])
                    {
                        string[] values = (string[])multiValueRoute.Value;
                        for (int i = 0; i < values.Length; i++)
                        {
                            newRouteDictionary.Add(multiValueRoute.Key + "[" + i + "]", values[i]);
                        }
                        newRouteDictionary.Remove(multiValueRoute.Key);
                    }
                    else if (multiValueRoute.Value is bool[])
                    {
                        bool[] values = (bool[])multiValueRoute.Value;
                        for (int i = 0; i < values.Length; i++)
                        {
                            newRouteDictionary.Add(multiValueRoute.Key + "[" + i + "]", values[i]);
                        }
                        newRouteDictionary.Remove(multiValueRoute.Key);
                    }
                }
            }

            if (!newRouteDictionary.ContainsKey("sortDir"))
            {
                newRouteDictionary.Add("sortDir", querySortCol == sortColumn ? oppositeQuerySortDir : (int)SortDirection.Asc);
            }
            else
            {
                newRouteDictionary["sortDir"] = querySortCol == sortColumn ? oppositeQuerySortDir : (int)SortDirection.Asc;
            }
            if (!newRouteDictionary.ContainsKey("sortCol"))
            {
                newRouteDictionary.Add("sortCol", sortColumn.ToString());
            }

            string keyword = html.ViewContext.HttpContext.Request.QueryString["keyword"];

            if (keyword != null && !newRouteDictionary.ContainsKey("keyword"))
            {
                newRouteDictionary.Add("keyword", keyword);
            }

            string index = html.ViewContext.HttpContext.Request.QueryString["index"];

            if (index != null && !newRouteDictionary.ContainsKey("index"))
            {
                newRouteDictionary.Add("index", index);
            }

            htmlAttributes = htmlAttributes ?? new Dictionary <string, object>();
            if (htmlAttributes.ContainsKey("class"))
            {
                htmlAttributes["class"] += " " + (querySortCol == sortColumn ? (querySortDir == (int)SortDirection.Asc ? "headerSortUp" : "headerSortDown") : "unsorted-header");
            }
            else
            {
                htmlAttributes.Add("class", querySortCol == sortColumn ? (querySortDir == (int)SortDirection.Asc ? "headerSortUp" : "headerSortDown") : "unsorted-header");
            }

            htmlAttributes.Add("id", string.Format("sortable-header-{0}-{1}", actionName, querySortCol.ToString()));

            if (controllerName == null)
            {
                return(LinkExtensions.ActionLink(html, linkText, actionName, controllerName, newRouteDictionary, htmlAttributes));
            }
            else
            {
                return(LinkExtensions.ActionLink(html, linkText, actionName, newRouteDictionary, htmlAttributes));
            }
        }