Exemplo n.º 1
0
        private static MvcHtmlString MvcCaptcha(this HtmlHelper helper, string actionName, string controllerName, MvcCaptchaOptions options)
        {
            if (options == null)
            {
                options = new MvcCaptchaOptions();
            }
            MvcCaptchaImage mvcCaptchaImage = new MvcCaptchaImage(options);
            HttpContext.Current.Session.Add(mvcCaptchaImage.UniqueId, mvcCaptchaImage);
            UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            StringBuilder stringBuilder = new StringBuilder(1500);
            stringBuilder.Append("\r\n<!--MvcCaptcha 1.1 for ASP.NET MVC 2 RC Copyright:2009-2010 Webdiyer (http://www.webdiyer.com)-->\r\n");
            stringBuilder.Append("<input type=\"hidden\" name=\"_mvcCaptchaGuid\" id=\"_mvcCaptchaGuid\"");
            if (options.DelayLoad)
            {
                stringBuilder.Append("/><script language=\"javascript\" type=\"text/javascript\">if (typeof (jQuery) == \"undefined\") { alert(\"jQuery脚本库未加载,请检查!\"); }");
                stringBuilder.Append("var _mvcCaptchaPrevGuid = null,_mvcCaptchaImgLoaded = false;function _loadMvcCaptchaImage(){");
                stringBuilder.Append("if(!_mvcCaptchaImgLoaded){$.ajax({type:'GET',url:'");
                stringBuilder.Append(urlHelper.Action("MvcCaptchaLoader", "_MvcCaptcha", new RouteValueDictionary
                {

                    {
                        "area",
                        null
                    }
                }));
                stringBuilder.Append("?'+_mvcCaptchaPrevGuid,global:false,success:function(data){_mvcCaptchaImgLoaded=true;");
                stringBuilder.Append("$(\"#_mvcCaptchaGuid\").val(data);_mvcCaptchaPrevGuid=data;$(\"#");
                stringBuilder.Append(options.CaptchaImageContainerId).Append("\").html('");
                stringBuilder.Append(MvcCaptchaHelper.CreateImgTag(urlHelper.Action(actionName, controllerName, new RouteValueDictionary
                {

                    {
                        "area",
                        null
                    }
                }) + "?'+data+'", options, null));
                stringBuilder.Append("');}});} };function _reloadMvcCaptchaImage(){_mvcCaptchaImgLoaded=false;_loadMvcCaptchaImage();};$(function(){");
                stringBuilder.Append("if($(\"#").Append(options.ValidationInputBoxId).Append("\").length==0){alert(\"未能找到验证码输入文本框,请检查ValidationInputBoxId属性是否设置正确!\");}");
                stringBuilder.Append("if($(\"#").Append(options.CaptchaImageContainerId).Append("\").length==0){alert(\"未能找到验证码图片父容器,请检查CaptchaImageContainerId属性是否设置正确!\");}");
                stringBuilder.Append("$(\"#").Append(options.ValidationInputBoxId);
                stringBuilder.Append("\").bind(\"focus\",_loadMvcCaptchaImage)});</script>");
            }
            else
            {
                stringBuilder.AppendFormat(" value=\"{0}\" />", mvcCaptchaImage.UniqueId);
                stringBuilder.Append(MvcCaptchaHelper.CreateImgTag(urlHelper.Action(actionName, controllerName, new RouteValueDictionary
                {

                    {
                        "area",
                        null
                    }
                }) + "?" + mvcCaptchaImage.UniqueId, options, mvcCaptchaImage.UniqueId));
                stringBuilder.Append("<script language=\"javascript\" type=\"text/javascript\">function _reloadMvcCaptchaImage(){var ci=document.getElementById(\"");
                stringBuilder.Append(mvcCaptchaImage.UniqueId);
                stringBuilder.Append("\");var sl=ci.src.length;if(ci.src.indexOf(\"&\")>-1)sl=ci.src.indexOf(\"&\");ci.src=ci.src.substr(0,sl)+\"&\"+(new Date().valueOf());}</script>");
            }
            stringBuilder.Append("\r\n<!--MvcCaptcha 1.1 for ASP.NET MVC 2 RC Copyright:2009-2010 Webdiyer (http://www.webdiyer.com)-->\r\n");
            return MvcHtmlString.Create(stringBuilder.ToString());
        }
Exemplo n.º 2
0
        public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string src, string altText, UrlHelper url, string actionName, string controllerName, dynamic routeValues, Dictionary<string, string> linkAttributes, Dictionary<string, string> imageAttributes)
        {
            var linkBuilder = new TagBuilder("a");
            linkBuilder.MergeAttribute("href", routeValues == null ? url.Action(actionName, controllerName) : url.Action(actionName, controllerName, routeValues));

            var imageBuilder = new TagBuilder("img");
            imageBuilder.MergeAttribute("src", url.Content(src));
            imageBuilder.MergeAttribute("alt", altText);

            if (linkAttributes != null)
            {
                foreach (KeyValuePair<string, string> attribute in linkAttributes)
                {
                    if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value))
                    {
                        linkBuilder.MergeAttribute(attribute.Key, attribute.Value);
                    }
                }
            }

            if (imageAttributes != null)
            {
                foreach (KeyValuePair<string, string> attribute in imageAttributes)
                {
                    if (!string.IsNullOrWhiteSpace(attribute.Key) && !string.IsNullOrWhiteSpace(attribute.Value))
                    {
                        imageBuilder.MergeAttribute(attribute.Key, attribute.Value);
                    }
                }
            }

            linkBuilder.InnerHtml = MvcHtmlString.Create(imageBuilder.ToString(TagRenderMode.SelfClosing)).ToString();
            return MvcHtmlString.Create(linkBuilder.ToString());
        }
 protected internal override IEnumerable<SitemapNode> GetSitemapNodes(UrlHelper urlHelper, HttpContextBase httpContext)
 {
     yield return new SitemapNode(urlHelper.Action("Index", "Home")) { Priority = 1 };
     yield return new SitemapNode(urlHelper.Action("Info", "Home")) { Priority = .25m };
     yield return new SitemapNode(urlHelper.Action("GettingStarted", "Home")) { Priority = 1 };
     yield return new SitemapNode(urlHelper.Action("Downloads", "Home")) { Priority = .25m };
 }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            if (!_fbClientProvider.IsAuthenticatedWithFb())
            {
                if (filterContext.ActionParameters.ContainsKey("request_ids"))
                {
                    var urlHelper = new UrlHelper(filterContext.RequestContext);
                    string redirectUrl = urlHelper.Action(
                        actionName: filterContext.ActionDescriptor.ActionName,
                        controllerName: filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                        routeValues: new RouteValueDictionary(filterContext.ActionParameters));

                    string url = urlHelper.Action(
                        actionName: "FacebookLogin",
                        controllerName: "Facebook",
                        routeValues:
                            new { state = HttpServerUtility.UrlTokenEncode(Encoding.UTF8.GetBytes(redirectUrl)) });

                    filterContext.Result = new RedirectResult(url);

                }
            }
        }
Exemplo n.º 5
0
 public static MvcHtmlString EmployeeImageRight(this HtmlHelper helper, Employee item)
 {
     var url = new UrlHelper(helper.ViewContext.RequestContext);
     var path = HttpContext.Current.Server.MapPath("~/public/userfiles/employees/" + item.Id + ".jpg");
     if (File.Exists(path))
     {
         return MvcHtmlString.Create(
             string.Format("<a href='{3}' class='employee-photo top-photo'><img title='{1}'  src='{2}' /></a>",
                 url.Content("~/public/images/pix.gif"),
                 item.FullName,
                 url.Content("~/public/userfiles/employees/" + item.Id + ".jpg"),
                 url.Action("Card", "Employees", new { item.Id })
             )
         );
     }
     else
     {
         return MvcHtmlString.Create(
       string.Format("<a href='{3}' class='employee-photo'><img title='{1}' style='background-size: 100%;background-image: url({2})' src='{0}' /></a>",
           url.Content("~/public/images/pix.gif"),
           item.FullName,
           url.Content("~/public/images/picture_bg.jpg"),
           url.Action("Card", "Employees", new { item.Id })
       )
   );
     }
 }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var urlHelper = new System.Web.Mvc.UrlHelper(filterContext.RequestContext);

            var currentUser = _context.Users.Where(u => u.Email == HttpContext.Current.User.Identity.Name).FirstOrDefault();

            if (currentUser != null)
            {
                if (currentUser.RoleId == 1)
                {
                    var IfEmployeeHasProfile = _context.Employees.Where(e => e.Id == currentUser.Id).FirstOrDefault();
                    if (IfEmployeeHasProfile == null)
                    {
                        filterContext.Result = new RedirectResult(urlHelper.Action("Create", "Employees"));
                    }
                }

                if (currentUser.RoleId == 2)
                {
                    var IfCompanyHasProfile = _context.Companies.Where(e => e.Id == currentUser.Id).FirstOrDefault();

                    if (IfCompanyHasProfile == null)
                    {
                        //filterContext.Result = new RedirectResult(urlHelper.Action("Create", "Companies"));
                        filterContext.Result = new RedirectResult(urlHelper.Action("Create", "Companies"));
                    }
                }
            }


            base.OnActionExecuting(filterContext);
        }
Exemplo n.º 7
0
 public static string CreateUrl(User user, UrlHelper urlHelper, HttpRequestBase request)
 {
     if (!user.IsPublicViewer)
         return urlHelper.Action(MVC.Account.Register(user.InvitationCode), request.Url.Scheme);
     else
         return urlHelper.Action(MVC.Account.PublicViewerLogOn(user.InvitationCode), request.Url.Scheme);
 }
        public JsonResult JsonExternalLogin(LoginModel model, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                //Step 1: Get data from Sp and check it
                AccountBL Ab = new AccountBL();
                ContactDetails cd = new ContactDetails();
                cd = Ab.CheckLogin(model.UserName, model.Password);
                if (cd.CustomerID > 0)
                {
                    //cd.CustomerID = 0;
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    SiteSession siteSession = new SiteSession(cd);
                    SessionHelper.UserSession = siteSession;

                    UrlHelper u = new UrlHelper(HttpContext.Request.RequestContext);
                    string url = string.Empty;
                    if (SessionHelper.UserSession.RoleID == UserRole.SuperAdmin ||
                        SessionHelper.UserSession.RoleID == UserRole.Admin||
                    SessionHelper.UserSession.RoleID == UserRole.Staff)
                        url = u.Action("Index", "Search", null);
                    else
                        url = u.Action("Index", "SetupCustomer", null);

                    return Json(new { success = true, redirect = string.IsNullOrEmpty(ReturnUrl) ? url : ReturnUrl });
                }
                else
                {
                    ModelState.AddModelError("", "Please provide valid User Name/Password.");
                }
            }
            return Json(new { errors = KeyValue.GetErrorsFromModelState(ViewData) });
        }
Exemplo n.º 9
0
        private string BuildUrl(ControllerContext filterContext)
        {
            UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
            string url;

            if (!string.IsNullOrEmpty(RouteName))
            {
                url = urlHelper.RouteUrl(RouteName);
            }
            else if (!string.IsNullOrEmpty(ControllerName) && !string.IsNullOrEmpty(ActionName))
            {
                url = urlHelper.Action(ActionName, ControllerName);
            }
            else if (!string.IsNullOrEmpty(ActionName))
            {
                url = urlHelper.Action(ActionName);
            }
            else
            {
                url = filterContext.HttpContext.Request.RawUrl;
            }

            url += "?" + filterContext.HttpContext.Request.QueryString;
            url = url.TrimEnd('?');

            return url;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!LoginCenter.IsUserLogin() || LoginCenter.CurrentUser.Role == Role.Company) return;

            var onLine = HttpContext.Current.Application[LotterySystem.M_ONLINEUSERCOUNT] as IDictionary<int, Pair<string, Role>>;
            string sessionId = HttpContext.Current.Session.SessionID;
            int userId = onLine.Where(it => it.Value.Key == sessionId).Select(it => it.Key).SingleOrDefault();
            if (!onLine.ContainsKey(userId))
            {
                LoginCenter lotinCentre = new LoginCenter();
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = new JsonResultModel
                        {
                            IsSuccess = false,
                            Message = Resource.LoginByOtherOne
                        }
                    };
                }
                else
                {
                    var urlHelper = new UrlHelper(filterContext.RequestContext);
                    string actionUrl = urlHelper.Action("Error", "Prompt");
                    string loginUrl = urlHelper.Action(LoginCenter.CurrentUser.Role == Role.Guest ? "Login" : "Agent", "Member");
                    string redirectUrl = string.Format("{0}?Url={1}&Msg={2}", actionUrl, loginUrl, Resource.LoginByOtherOne);
                    filterContext.Result = new RedirectResult(redirectUrl);
                }
                lotinCentre.Logout();
            }
        }
Exemplo n.º 11
0
        private static ActionResult GetRedirectResultByExceptionType(string errType, ExceptionContext exceptionContext)
        {
            var urlHelper = new UrlHelper(exceptionContext.HttpContext.Request.RequestContext);
            var exception = exceptionContext.Exception;
            var iController = exceptionContext.Controller as IControllerProperties;
            var isAdminController = iController != null && iController.IsAdminController;

            if (exception is UnauthorizedAccessException)
                errType = "unauthorized";
            else if (exception is InvalidMonthException)
                errType = "invalid-month";

            ActionResult redirectTo = isAdminController ? new RedirectResult(urlHelper.Action("Error","Admin", new { Area = "Admin", err = errType })) 
                                                        : new RedirectResult(urlHelper.Action("Error", "Home", new { Area = "", err = errType }));
            
            if (exception is UrlNotFoundException)
                redirectTo = new RedirectToRouteResult("Error404", new RouteValueDictionary());
            
            if (exception is InvalidThemeException)
                redirectTo = new RedirectToRouteResult("InvalidTheme", new RouteValueDictionary());

            if (exception is SqlException)
                redirectTo = new RedirectToRouteResult("InitializeDatabase", new RouteValueDictionary());

            return redirectTo;
        }
Exemplo n.º 12
0
        public static MvcHtmlString BreadcrumbFromPath(this HtmlHelper html, string element, PaneState.PaneType type, string path, NameValueCollection requestParams, bool active = false)
        {
            var liTag = new TagBuilder("li");
            var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
            string url = "";
            switch (type)
            {
                case PaneState.PaneType.Left:
                    url = urlHelper.Action("Index", new { leftPath = path, rightPath = requestParams["rightPath"] });
                    break;
                case PaneState.PaneType.Right:
                    url = urlHelper.Action("Index", new { leftPath = requestParams["leftPath"], rightPath = path });
                    break;
            }
            var aTag = new TagBuilder("a");
            aTag.MergeAttribute("href", url);
            aTag.InnerHtml = element;

            liTag.InnerHtml = aTag.ToString();
            if (active)
            {
                liTag.AddCssClass("active");
            }

            return MvcHtmlString.Create(liTag.ToString());
        }
Exemplo n.º 13
0
        public override void InitializeSidebar(Sidebar sidebar, UrlHelper urlHelper)
        {
            sidebar.AddSidebarItem(SidebarObjectType.ViewDisplay, "Search", urlHelper.Action("Search", "Pages", new { area = "Admin" }));
            sidebar.AddSidebarItem(SidebarObjectType.ViewDisplay, "Details", urlHelper.Action("Details", "Pages", new { area = "Admin", ActionId = ActiveSystemPage.ActionId }));

            base.InitializeSidebar(sidebar, urlHelper);
        }
Exemplo n.º 14
0
 public ChannelItemViewModel(Channel channel, UrlHelper url, Account account)
 {
     name = channel.Name;
     isOwner = channel.ChannelMembers.First(c => c.AccountId == account.Id).IsOwner;
     channelUrl = url.Action("Index", new { id = channel.Id.ToString("N") });
     settingsUrl = url.Action("Settings", new { id = channel.Id.ToString("N") });
 }
Exemplo n.º 15
0
        public static MvcHtmlString ActionButton(this HtmlHelper html, string linkText, string action, string controllerName, string iconClass, string value = null)
        {
            //<a href="/@lLink.ControllerName/@lLink.ActionName" title="@lLink.LinkText"><i class="@lLink.IconClass"></i><span class="">@lLink.LinkText</span></a>
            var lURL = new UrlHelper(html.ViewContext.RequestContext);

            // build the <span class="">@lLink.LinkText</span> tag
            var lSpanBuilder = new TagBuilder("span");
            lSpanBuilder.MergeAttribute("class", "");
            lSpanBuilder.SetInnerText(linkText);
            string lSpanHtml = lSpanBuilder.ToString(TagRenderMode.Normal);

            // build the <i class="@lLink.IconClass"></i> tag
            var lIconBuilder = new TagBuilder("i");
            lIconBuilder.MergeAttribute("class", iconClass);
            string lIconHtml = lIconBuilder.ToString(TagRenderMode.Normal);

            // build the <a href="@lLink.ControllerName/@lLink.ActionName" title="@lLink.LinkText">...</a> tag
            var lAnchorBuilder = new TagBuilder("a");

            if (string.IsNullOrEmpty(value))
            {
            lAnchorBuilder.MergeAttribute("href", lURL.Action(action, controllerName));
            }
            else
            {
            lAnchorBuilder.MergeAttribute("href", lURL.Action(action, controllerName, new { id = value }));
            }

            lAnchorBuilder.InnerHtml = lIconHtml + lSpanHtml; // include the <i> and <span> tags inside
            string lAnchorHtml = lAnchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(lAnchorHtml);
        }
Exemplo n.º 16
0
 /// <summary>
 /// CTR
 /// </summary>
 public ShippingCostIndex()
 {
     var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
     UpdateShippingCategoryUrl = url.Action(MVC.Admin.ShippingCosts.UpdateShippingCategory());
     CreateShippingCategoryUrl = url.Action(MVC.Admin.ShippingCosts.CreateShippingCategory());
     UpdateShippingCostsUrl = url.Action(MVC.Admin.ShippingCosts.Update());
 }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            var url = new UrlHelper(filterContext.RequestContext);
            var id = filterContext.RouteData.Values["id"];

            if (filterContext.Controller.GetType() == typeof(DataCollectionController))
            {
                var projectId = filterContext.RouteData.Values["projectId"];

                filterContext.Controller.ViewBag.Steps = new List<Step>
                                                             {
                                                                 new Step {Url = url.Action("Step1", "DataCollection", new {id, projectId}), Name = "Section 1"},
                                                                 new Step {Url = url.Action("Step2", "DataCollection", new {id, projectId}), Name = "Section 2"}
                                                             };
                filterContext.Controller.ViewBag.MaxStep = 2;
            }
            else if (filterContext.Controller.GetType() == typeof(ApprovalController))
            {
                filterContext.Controller.ViewBag.Steps = new List<Step>
                                                             {
                                                                 new Step {Url = url.Action("Step1", "Approval", new {id }), Name = "Section 1"},
                                                                 new Step {Url = url.Action("Step2", "Approval", new {id }), Name = "Section 2"},
                                                                 new Step {Url = url.Action("Confirm", "Approval", new {id}), Name = "Confirm"}
                                                             };
                filterContext.Controller.ViewBag.MaxStep = 2;
            }
        }
Exemplo n.º 18
0
        // Extension method
        public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string controllerName, string imagePath, string alt, string anchorCssClass, string imgCssClass, object routeAttributes)
        {
            var url = new UrlHelper(html.ViewContext.RequestContext);

            // build the <img> tag
            var imgBuilder = new TagBuilder("img");
            imgBuilder.MergeAttribute("src", url.Content(imagePath));
            imgBuilder.MergeAttribute("alt", alt);
            if(imgCssClass != null)
                imgBuilder.AddCssClass(imgCssClass);
            string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

            // build the <a> tag
            var anchorBuilder = new TagBuilder("a");
            if (routeAttributes == null)
                anchorBuilder.MergeAttribute("href", url.Action(action, controllerName));
            else
                anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeAttributes));

            anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
            if(anchorCssClass != null)
                anchorBuilder.AddCssClass(anchorCssClass);
            string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(anchorHtml);
        }
Exemplo n.º 19
0
        public SendingMailResult SendCommentReplyNotification(CommentReplyEmailNotificationData data, CommentReplyType replyType)
        {
            var urlHelper = new UrlHelper(_httpContext.Request.RequestContext);

            var link = string.Empty;

            switch (replyType)
            {
                case CommentReplyType.ReplyToArticleComment:
                    link = urlHelper.Action(MVC.Article.ActionNames.Index, MVC.Article.Name, new
                    {
                        title = UrlExtensions.ResolveTitleForUrl(data.PostTitle),
                        id = data.PostId
                    }, _httpContext.Request.Url.Scheme);
                    break;
                case CommentReplyType.ReplyToPageComment:
                    link = urlHelper.Action(MVC.Page.ActionNames.Index, MVC.Page.Name, new
                    {
                        title = UrlExtensions.ResolveTitleForUrl(data.PostTitle),
                        id = data.PostId
                    }, _httpContext.Request.Url.Scheme);
                    break;
                case CommentReplyType.ReplyToPostComment:
                    link = urlHelper.Action(MVC.Post.ActionNames.Index, MVC.Post.Name, new
                    {
                        title = UrlExtensions.ResolveTitleForUrl(data.PostTitle),
                        id = data.PostId
                    }, _httpContext.Request.Url.Scheme);
                    break;
            }

            link += "#comment-" + data.CommentId;

            var model = new CommentReplyNotificationModel
            {
                FromUserName = data.FromUserName,
                ToUserName = data.ToUserName,
                PostId = data.PostId,
                PostTitle = data.PostTitle,
                CommentText = data.CommentText,
                CommentLink = link
            };

            var htmlText = _viewConvertor.RenderRazorViewToString(MVC.EmailTemplates.Views._CommentReplyNotification, model);


            var result = Send(new MailDocument
             {
                 Body = htmlText,
                 Subject =
                     string.Format("شما پاسخی از طرف {0} در مطلب {1} دریافت کرده اید.", data.FromUserName, data.PostTitle),
                 ToEmail = data.ToEmail
             });


            return result;
        }
Exemplo n.º 20
0
        public void It_returns_translated_routes()
        {
            var translations = new FluentTranslationProvider();

            translations.AddTranslations().ForController<TranslationController>()
                .AreaUrl(new Dictionary<string, string>
                {
                    { "es", "es-Area" }
                })
                .RoutePrefixUrl(new Dictionary<string, string>
                {
                    { "es", "es-Prefix" }
                })
                .RouteUrl(c => c.Index(), new Dictionary<string, string>
                {
                    { "es", "es-Index" }
                });

            translations.AddTranslations()
                .ForKey("CustomAreaKey", new Dictionary<string, string>
                {
                    { "es", "es-CustomArea" }
                })
                .ForKey("CustomPrefixKey", new Dictionary<string, string>
                {
                    { "es", "es-CustomPrefix" }
                })
                .ForKey("CustomRouteKey", new Dictionary<string, string>
                {
                    { "es", "es-CustomIndex" }
                });

            RouteTable.Routes.Clear();
            RouteTable.Routes.MapAttributeRoutes(config =>
            {
                config.AddRoutesFromController<TranslationController>();
                config.AddRoutesFromController<TranslationWithCustomKeysController>();
                config.AddTranslationProvider(translations);
            });

            var requestContext = MockBuilder.BuildRequestContext();

            // Default culture
            var urlHelper = new UrlHelper(requestContext, RouteTable.Routes);
            Assert.That(urlHelper.Action("Index", "Translation", new { area = "Area" }),
                        Is.EqualTo("/Area/Prefix/Index"));

            // es-ES culture
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-ES");
            Assert.That(urlHelper.Action("Index", "Translation", new { area = "Area" }),
                        Is.EqualTo("/es-Area/es-Prefix/es-Index"));

            // es culture
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("es");
            Assert.That(urlHelper.Action("Index", "Translation", new { area = "Area" }),
                        Is.EqualTo("/es-Area/es-Prefix/es-Index"));
        }
 public string ToJson(UrlHelper url)
 {
     return JsonConvert.SerializeObject(new
     {
         items = Items,
         messages = Messages,
         create = url.Action("create", "todos"),
         update = url.Action("update", "todos")
     });
 }
Exemplo n.º 22
0
 public static MenuItem MainMenu(UrlHelper url)
 {
     Menu.DefaultDisabledClass = "disabled";
     Menu.DefaultSelectedClass = "selected";
     return Menu.Begin(
         Menu.Link(url.Action(MVC.Files.Index()), "Home"),
         Menu.Link(url.Action(MVC.Files.Search()), "Search"),
         Menu.Link("http://microsoft.com", "Big Blue"),
         Menu.Link("http://google.com", "Google")).SetListClass("menu");
 }
Exemplo n.º 23
0
		public static IList<MenuItem> GetTopMenu(UrlHelper url)
		{
			var items = new List<MenuItem>
			{
				new MenuItem {Title = "Back To Blog", Url = url.RouteUrl("homepage"), Type = MenuButtonType.Plain},
				new MenuItem {Title = "Posts", Url = url.Action("Index", "Posts"), Type = MenuButtonType.Plain},
                new MenuItem {Title = "Add new post", Url = url.Action("Add", "Posts"), Type = MenuButtonType.Add},
				new MenuItem {Title = "Sections", Url = url.Action("Index", "Sections"), Type = MenuButtonType.Plain},
                new MenuItem {Title = "Add new section", Url = url.Action("Add", "Sections"), Type = MenuButtonType.Add},
				new MenuItem {Title = "Users", Url = url.Action("Index", "Users"), Type = MenuButtonType.Plain},
                new MenuItem {Title = "Add new user", Url = url.Action("Add", "Users"), Type = MenuButtonType.Add},
				new MenuItem {Title = "Tools", Type = MenuButtonType.Toggle,
                    SubMenus = new List<MenuItem>
                    {
                        new MenuItem {Title = "Settings", Url = url.Action("Index", "Settings"), Type = MenuButtonType.Plain},
                        new MenuItem {Title = "RSS Future Access", Url = url.Action("RssFutureAccess", "Settings"), Type = MenuButtonType.Plain},
                        new MenuItem {Title = "Reddit submission", Url = url.Action("RedditSubmission", "Settings"), Type = MenuButtonType.Plain},
                    }
				},
			};

			AnalyzeMenuItems(items, url.RequestContext.HttpContext.Request.Url ?? new Uri("/"));
			

			return items;
		}
Exemplo n.º 24
0
        public static string CurrentActionLink(this HtmlHelper helper, UrlHelper url)
        {
            string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
            string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
            string currentAreaName = (string)helper.ViewContext.RouteData.Values["area"];

            if (currentAreaName.IsNullOrEmpty())
                return url.Action(currentActionName, currentControllerName);
            else
                return url.Action(currentActionName, currentControllerName, new { area = currentAreaName });
        }
Exemplo n.º 25
0
        public ActionResult Rss()
        {
            var urlHelper = new UrlHelper(this.Request.RequestContext);
            var feed = new SyndicationFeed(@"Лента ближайших событий УО ""ПГАЭК""", "Подписка",
                new Uri(urlHelper.Action("Rss", "Events", null, "http")));

            var lastEvents = eventsRepository.Where(ar => ar.Date >= DateTime.Today).OrderByDescending(ar => ar.Date).Take(10);
            var items = lastEvents.Select(ev => new SyndicationItem(ev.Title, ArticleHelper.GetShortenArticleText(ev.Text),
                new Uri(urlHelper.Action("List", "Events", null, "http")))).ToList();
            feed.Items = items;
            return new RssResult { Feed = feed };
        }
Exemplo n.º 26
0
        public ActionResult Rss()
        {
            var urlHelper = new UrlHelper(this.Request.RequestContext);
            var feed = new SyndicationFeed(@"Лента новостей УО ""ПГАЭК""", "Подписка",
                new Uri(urlHelper.Action("Rss", "News", null, "http")));

            var lastNews = articlesRepository.GetAll().OrderByDescending(ar => ar.PostedAt).Take(10);
            var items = lastNews.Select(nw => new SyndicationItem(nw.Title, ArticleHelper.GetShortenArticleText(nw.Text),
                new Uri(urlHelper.Action("Show", "News", new {id = nw.Id}, "http")))).ToList();
            feed.Items = items;

            return new RssResult {Feed = feed};
        }
        private void Initialize(ActionExecutingContext filterContext)
        {
            var urlHelper = new UrlHelper(filterContext.RequestContext);
            _invalidUrls = new[]
            {
                urlHelper.Action(MVC.Identity.SignIn()).WithoutTrailingSlash(),
                urlHelper.Action(MVC.Identity.SignOut()).WithoutTrailingSlash(),
            };

            if (filterContext.HttpContext.Request.Url == null)
                throw new InvalidOperationException(
                    "An unexpected error has occurred (HttpRequestBase.Url was null).");
            _requestUri = filterContext.HttpContext.Request.Url;
        }
Exemplo n.º 28
0
        public static List<Menu> GetMenu(RequestContext _context)
        {
            UrlHelper Url = new UrlHelper(_context);
            List<Menu> menus = new List<Menu>();
            Menu m1 = new Menu("a10", null, "首页", "menu-icon fa fa-home", Url.Content("~/Home/Index"));
            Menu m2 = new Menu("a11", null, "人员列表", "menu-icon fa fa-list", Url.Content("~/Human/List"));

            Menu m4 = new Menu("a15", null, "人员信息统计", "menu-icon fa fa-bar-chart-o", "#");
            m4.AddChild("a1501", "按年龄段统计", string.Empty, Url.Action("NianLing", "TongJi"));
            m4.AddChild("a1502", "按学历统计", string.Empty, Url.Action("XueLi", "TongJi"));
            m4.AddChild("a1503", "按政治面貌统计", string.Empty, Url.Action("ZhengZhi", "TongJi"));
            m4.AddChild("a1504", "按入职时间统计", string.Empty, Url.Action("RuZhi", "TongJi"));
            m4.AddChild("a1505", "按岗位统计", string.Empty, Url.Action("GangWei", "TongJi"));
            m4.AddChild("a1506", "按职称统计", string.Empty, Url.Action("ZhiCheng", "TongJi"));
            Menu m3 = new Menu("a12", null, "系统设置", "menu-icon fa fa-pencil-square-o", "#");

            m3.AddChild("a13", "数据字典栏目", string.Empty, Url.Action("Index", "DicLan"));
            m3.AddChild("a14", "数据字典", string.Empty, Url.Action("Index", "DicLan"));

            menus.Add(m1);
            menus.Add(m2);
            menus.Add(m4);
            menus.Add(m3);

            return menus;
        }
Exemplo n.º 29
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var urlHelper = new UrlHelper(filterContext.RequestContext);

            // if these are null, then the model binder will throw error anyways
            var projectId = Convert.ToInt32(filterContext.RequestContext.HttpContext.Request.Params["projectId"]);
            var id = Convert.ToInt32(filterContext.RouteData.Values["id"]); // project step id
            var logon = filterContext.RequestContext.HttpContext.User.Identity.Name;

            var db = new SquareContext();

            // load pstep
            var pStep = db.ProjectSteps.Include("Project").Include("Project.ProjectWorkers")
                                       .Include("Project.ProjectWorkers.User")
                                       .Include("Project.ProjectWorkers.Role")
                                       .Include("Step").Include("Step.SquareType")
                                       .Where(a => a.Project.Id == projectId && a.Id == id).Single();

            // figure out if the current user has access

            // validate their step access

            Check.Require(pStep != null, "pstep is required.");

            var project = pStep.Project;

            if (!_projectService.IsStepWorking(pStep.Id))
            {
                // this project is not valid for working
                // admin needs to change status
                if (project.ProjectWorkers.Where(a => a.User.Username == logon
                    && a.Role.Name == RoleNames.RoleProjectManager).Any())
                {
                    filterContext.Controller.TempData["ErrorMessage"] = string.Format(Messages.Manager_NotValidForWork,
                                                                                      pStep.Step.Order,
                                                                                      pStep.Step.SquareType.Name);
                    filterContext.Result = new RedirectResult(urlHelper.Action("ChangeStatus", "Project", new { id = pStep.Project.Id }));
                }
                else
                {
                    // regular user, can't access step
                    filterContext.Controller.TempData["ErrorMessage"] = string.Format(Messages.NotValidForWork,
                                                                                      pStep.Step.Order,
                                                                                      pStep.Step.SquareType.Name);
                    filterContext.Result = new RedirectResult(urlHelper.Action("Details", "Project", new { id = projectId }));
                }
            }

            base.OnActionExecuting(filterContext);
        }
Exemplo n.º 30
0
 public static OpenGraph OpenGraph(this Person person, string siteName, RequestContext context)
 {
     if (person.UploadedFile == null) return null;
     var urlHelper = new UrlHelper(context);
     var imageUrl = context.HttpContext.Request.UrlBase() + urlHelper.Action("display", "upload", new { category = person.UploadedFile.Category, fileName = person.UploadedFile.FileName });
     var pageUrl = context.HttpContext.Request.UrlBase() + urlHelper.Action("details", "authors", new { id = person.Id });
     return new OpenGraph
     {
         Title = person.FullName,
         Type = "article",
         ImageUrl = imageUrl,
         Url = pageUrl,
         SiteName = siteName
     };
 }
Exemplo n.º 31
0
        protected override string GetUrl(ControllerContext context)
        {
            var urlHelper = new UrlHelper(context.RequestContext);

            string actionUrl = string.Empty;
            if (this.routeValues == null)
                actionUrl = urlHelper.Action(this.action, this.routeValuesDict);
            else if (this.routeValues != null)
                actionUrl = urlHelper.Action(this.action, this.routeValues);
            else
                actionUrl = urlHelper.Action(this.action);

            string url = String.Format("{0}://{1}{2}", context.HttpContext.Request.Url.Scheme, context.HttpContext.Request.Url.Authority, actionUrl);
            return url;
        }
        public static MvcHtmlString CustomComboBoxWithCascadeFor <TModel, TValue>(this HtmlHelper <TModel> helper, Expression <Func <TModel, TValue> > expression, string entityTypeLookup, string customActionCascade, string controller, object htmlAttributes = null)
        {
            var    urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var    url       = urlHelper.Action(customActionCascade, controller);
            var    metadata  = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string value     = metadata.Model == null ? string.Empty : metadata.Model.ToString();

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

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

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

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

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

            var attributes = new RouteValueDictionary();

            attributes["controltype"]     = "kendoComboBoxForCustomData";
            attributes["serverFiltering"] = false.ToString();
            attributes["url"]             = url;
            attributes["placeHolder"]     = placeHolderString.Equals(string.Empty) ? PlaceHolder : placeHolderString;
            attributes["customType"]      = "text";
            attributes["parameter"]       = string.Join(",", paramControls);
            attributes["id"]   = fieldId;
            attributes["name"] = fieldId;

            var combox = helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes).ToString();

            return(new MvcHtmlString(combox));
        }
Exemplo n.º 34
0
        public static MvcHtmlString LinkWithSID(this System.Web.Mvc.UrlHelper Url, string Title, string ActionName, string ControllerName, object RouteValues, object HtmlAttributes)
        {
            string url = Url.Action(ActionName, ControllerName) + "?";

            if (RouteValues != null)
            {
                var RouteValuesProperties = RouteValues.GetType().GetProperties();
                foreach (var p in RouteValuesProperties)
                {
                    url += p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(RouteValues).ToString()) + "&";
                }
            }
            url += "sid=" + Url.RequestContext.HttpContext.Session["sid"];
            var attributes = " ";

            if (HtmlAttributes != null)
            {
                var HtmlAttributesProperties = HtmlAttributes.GetType().GetProperties();
                foreach (var p in HtmlAttributesProperties)
                {
                    attributes += p.Name + "=\"" + p.GetValue(HtmlAttributes) + "\" ";
                }
            }
            return(new MvcHtmlString("<a href=\"javascript:window.location='" + url + "'\"" + attributes + "/>" + HttpUtility.HtmlEncode(Title) + "</a>"));
        }
Exemplo n.º 35
0
        private static String GetUrl(System.Web.Mvc.UrlHelper urlHelper, String action, Int32 page, IDictionary <String, Object> args)
        {
            var routeValues = new RouteValueDictionary(args);

            routeValues.Add("page", page);
            return(urlHelper.Action(action, routeValues));
        }
Exemplo n.º 36
0
        public static async Task <PnpFileModel> GetAsync(FileHandlerActivationParameters parameters, System.Web.Mvc.UrlHelper url)
        {
            // Retrieve an access token so we can make API calls
            string accessToken = null;

            try
            {
                accessToken = await AuthHelper.GetUserAccessTokenSilentAsync(parameters.ResourceId);
            }
            catch (Exception ex)
            {
                return(GetError(parameters, ex));
            }

            // Read the details of the specified item
            GraphServiceClient graphServiceClient = GraphHelper.Default.GetGraphServiceClient(accessToken);
            IDriveRequest      request            = new DriveRequest(parameters.ItemUrls[0], graphServiceClient, Array.Empty <Option>());
            Drive drive = await request.GetAsync();

            return(new PnpFileModel(parameters)
            {
                Title = drive.Name,
                // Create uri to use to load the content
                PreviewUri = url.Action("PreviewInfo", new
                {
                    resourceId = parameters.ResourceId,
                    uri = parameters.ItemUrls[0] + "/content"
                })
            });
        }
Exemplo n.º 37
0
        //<< Fields

        public override void WriteInitializationScript(TextWriter writer)
        {
            var container = "document.body";

            var options = new Dictionary <string, object>(Events);

            options.Add("hideAddressBar", HideAddressBar);
            options.Add("updateDocumentTitle", UpdateDocumentTitle);
            options.Add("serverNavigation", ServerNavigation);

            if (Skin.HasValue())
            {
                options.Add("skin", Skin);
            }

            if (!WebAppCapable)
            {
                options.Add("webAppCapable", false);
            }

            if (Layout.HasValue())
            {
                options.Add("layout", Layout);
            }

            if (Loading.HasValue())
            {
                options.Add("loading", Loading);
            }

            if (Platform.HasValue())
            {
                options.Add("platform", Platform);
            }

            if (Transition.HasValue())
            {
                options.Add("transition", Transition);
            }

            if (Id.HasValue())
            {
                container = "\"" + Selector + "\"";
            }

            if (PushState)
            {
                options.Add("pushState", PushState);
                var url       = new System.Web.Mvc.UrlHelper(ViewContext.RequestContext);
                var routeData = ViewContext.RequestContext.RouteData.Values;
                var root      = url.Action(string.Empty, routeData);

                options.Add("root", Regex.Replace(root, "/$", "/"));
            }

            writer.Write(String.Format("jQuery(function(){{ new kendo.mobile.Application(jQuery({0}), {1}); }});", container, Initializer.Serialize(options)));

            base.WriteInitializationScript(writer);
        }
Exemplo n.º 38
0
        protected void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

            // Get the exception object.
            Exception exc = Server.GetLastError();

            // Handle HTTP errors
            if (exc != null && exc.GetType() == typeof(HttpException))
            {
                if (SiteConfigurationReader.EnableHttpErrorLog)
                {
                    ExceptionManager.Manage(exc);
                }
                // The Complete Error Handling Example generates
                // some errors using URLs with "NoCatch" in them;
                // ignore these here to simulate what would happen
                // if a global.asax handler were not implemented.
                if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
                {
                    return;
                }

                //Redirect HTTP errors to HttpError page
                //WebHelper.CurrentSession.Content.ErrorMessage = ExceptionManager.BuildErrorStack(exc);
                //UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                //Response.Redirect(url.Action(Constants.Actions.Error, Constants.Controllers.Home, new { Area="" }));
            }
            else
            {
                // Log the exception and notify system operators
                if (exc != null)
                {
                    if (exc.GetType() == typeof(CustomException))
                    {
                        WebHelper.CurrentSession.Content.ErrorMessage = exc.Message;
                    }
                    else
                    {
                        WebHelper.CurrentSession.Content.ErrorMessage = ExceptionManager.BuildErrorStack(exc);
                    }
                    ExceptionManager.Manage(exc);
                }
                try
                {
                    if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null && !HttpContext.Current.Request.Url.ToString().Contains("Error"))
                    {
                        UrlHelper url = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
                        Response.Redirect(url.Action(Constants.Actions.Error, Constants.Controllers.Home, new { Area = "" }));
                    }
                }
                catch { }
            }

            // Clear the error from the server
            Server.ClearError();
        }
Exemplo n.º 39
0
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            System.Web.Mvc.UrlHelper helper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);
            string link = helper.Action("Partial_Index", "Home2");

            if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith(".jpg") && HttpContext.Current.Request.UrlReferrer.Host != "localhost")
            {
                HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/imgs/forbid.png"));
                HttpContext.Current.Response.End();
            }
        }
Exemplo n.º 40
0
        public static Editor PrepairEditorWithName(Action <Editor> oninit, string name, bool isajax)
        {
            Editor editor = new Editor(System.Web.HttpContext.Current, name);

            editor.ClientFolder = "/richtexteditor/";
            //editor.ClientFolder = "/Content/richtexteditor/";
            //editor.ClientFolder = "/Scripts/richtexteditor/";

            editor.Text = "";

            var urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext);

            editor.AjaxPostbackUrl = urlHelper.Action("EditorAjaxHandler", "EditorAjax");

            if (oninit != null)
            {
                oninit(editor);
            }

            //try to handle the upload/ajax requests


            if (isajax)
            {
                return(editor);
            }

            //load the form data if any
            if (HttpContext.Current.Request.HttpMethod == "POST")
            {
                try
                {
                    string formdata = HttpContext.Current.Request.Form[editor.Name];
                    if (formdata != null)
                    {
                        editor.LoadFormData(formdata);
                    }
                }
                catch (Exception ex)
                {
                }
            }

            return(editor);
        }
Exemplo n.º 41
0
        /// <summary>
        /// 分页控件
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="index">当前页</param>
        /// <param name="count">总页数</param>
        /// <param name="provider">地址生成器</param>
        /// <param name="showCount">显示页码数量</param>
        /// <param name="isShowHomeAndLast">是否显示首页和末页</param>
        /// <param name="isShowPrevAndNext">是否显示上一页和下一页</param>
        /// <param name="isHomeAndLastInside">首页和末页是否显示在上一页和下一页的内侧</param>
        /// <param name="isShowInput">是否显示转跳输入框</param>
        /// <param name="isUseDefaultSubmitScript">是否使用默认转跳js</param>
        /// <param name="isWithQueryString">是否包含QueryString字符串</param>
        /// <param name="isUrlEncode">传递的参数是否需要编码</param>
        /// <param name="interval">中间的间隔内容模板;{0}:Class</param>
        /// <param name="itemTemplate">分页模板;{0}:页码,{1}:地址,{2}:Class</param>
        /// <param name="indexTemplate">当前页码模板;{0}:页码,{1}:Class</param>
        /// <param name="parentTemplate">父级模板;{0}:分页html代码</param>
        /// <param name="inputTemplate">输入框模板</param>
        /// <param name="submitTemplate">提交按钮模板</param>
        /// <param name="homeString">首页文字</param>
        /// <param name="lastString">末页文字</param>
        /// <param name="prevString">上一页文字</param>
        /// <param name="nextString">下一页文字</param>
        internal Pager(HtmlHelper helper, IPageModel model,
                       int showCount,
                       bool isShowHomeAndLast,
                       bool isShowPrevAndNext,
                       bool isHomeAndLastInside,
                       bool isShowInput,
                       bool isUseDefaultSubmitScript,
                       bool isWithQueryString,
                       bool isUrlEncode,
                       string interval,
                       string itemTemplate,
                       string indexTemplate,
                       string parentTemplate,
                       string inputTemplate,
                       string submitTemplate,
                       string homeString,
                       string lastString,
                       string prevString,
                       string nextString)
        {
            thisCounter = System.Threading.Interlocked.Increment(ref Counter);

            Index          = Math.Max(model.PageIndex, 1);
            Count          = Math.Max(0, model.PageCount);
            Index          = Math.Min(Index, Count);
            ShowCount      = Math.Min(Math.Max(3, showCount), Count);
            ItemTemplate   = itemTemplate;
            IndexTemplate  = indexTemplate;
            ParentTemplate = parentTemplate;
            InputTemplate  = inputTemplate;
            SubmitTemplate = submitTemplate;
            if (isWithQueryString)
            {
                QueryString = Util.GetUrlQuerys(helper.ViewContext.HttpContext.Request.Url.Query, isUrlEncode);
            }
            else
            {
                QueryString = new NameValueCollection();
            }
            if (model.UrlProvider == null)
            {
                UrlHelper = new System.Web.Mvc.UrlHelper(helper.ViewContext.RequestContext);
                var actionName = UrlHelper.RequestContext.RouteData.Values["action"] as String;

                Provider = page =>
                {
                    QueryString["page"] = page.ToString();
                    return(Util.UrlCombine(UrlHelper.Action(actionName), QueryString, isUrlEncode));
                };
            }
            else
            {
                Provider = page =>
                {
                    var values = new RouteValueDictionary(QueryString);
                    values["page"] = page;
                    return(model.UrlProvider(page, values));
                };
            }

            IsShowInput = isShowInput;
            IsUseDefaultSubmitScript = isUseDefaultSubmitScript;
            IsShowHomeAndLast        = isShowHomeAndLast;
            IsShowPrevAndNext        = isShowPrevAndNext;
            IsHomeAndLastInside      = isHomeAndLastInside;
            Interval   = interval;
            HomeString = homeString ?? String.Empty;
            LastString = lastString;
            PrevString = prevString ?? String.Empty;
            NextString = nextString ?? String.Empty;
        }
Exemplo n.º 42
0
        public static string AbsoluteActionLink(this UrlHelper helper, string action, string controller, object args)
        {
            var relUrl = helper.Action(action, controller, args);

            return(string.Format("{0}{1}", SiteRoot(helper.RequestContext.HttpContext), relUrl));
        }
 public static string AbsoluteAction(this UrlHelper url, string actionName, string controllerName, object routeValues)
 {
     return(url.Action(actionName, controllerName, routeValues, url.RequestContext.HttpContext.Request.Url.Scheme));
 }
Exemplo n.º 44
0
 public static string Action(this UrlHelper urlHelper, ActionResult result)
 {
     return(urlHelper.Action(result, null, null));
 }
Exemplo n.º 45
0
        private SiteMapNode CreateSiteMapFromRow(DXInfo.Models.aspnet_Sitemaps item)
        {
            if (_nodes.ContainsKey(item.Code))
            {
                throw new ProviderException(string.Format("重复节点Code={0},Title={1}", item.Code, item.Title));
            }
            SiteMapNode node = new SiteMapNode(this, item.Code);

            node["IsAuthorize"] = item.IsAuthorize.ToString();
            if (!string.IsNullOrEmpty(item.Url))
            {
                node.Title       = string.IsNullOrEmpty(item.Title) ? null : item.Title;
                node.Description = string.IsNullOrEmpty(item.Description) ? null : item.Description;
                node.Url         = string.IsNullOrEmpty(item.Url) ? null : item.Url;
            }
            else
            {
                node.Title       = string.IsNullOrEmpty(item.Title) ? null : item.Title;
                node.Description = string.IsNullOrEmpty(item.Description) ? null : item.Description;

                //IDictionary<string, object> routeValues = new Dictionary<string, object>();

                //if (string.IsNullOrEmpty(item.Controller))
                //    routeValues.Add("controller", "Home");
                //else
                //    routeValues.Add("controller", item.Controller);

                //if (string.IsNullOrEmpty(item.Action))
                //    routeValues.Add("action", "Index");
                //else
                //    routeValues.Add("action", item.Action);

                //if (!string.IsNullOrEmpty(item.ParaId))
                //    routeValues.Add("id", item.ParaId);



                HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current);
                RouteData          routeData   = RouteTable.Routes.GetRouteData(httpContext);

                if (routeData != null)
                {
                    //VirtualPathData virtualPath = routeData.Route.GetVirtualPath(new RequestContext(httpContext, routeData), new RouteValueDictionary(routeValues));
                    //string str = System.Web.Mvc.UrlHelper.GenerateUrl("", "", "", new RouteValueDictionary(routeValues), new RouteCollection(), httpContext, true);
                    System.Web.Routing.RequestContext rc  = new RequestContext(httpContext, routeData);
                    System.Web.Mvc.UrlHelper          url = new System.Web.Mvc.UrlHelper(rc);
                    RouteValueDictionary routeValues      = new RouteValueDictionary();

                    if (!string.IsNullOrEmpty(item.ParaId))
                    {
                        string[] paras = item.ParaId.Split('&');
                        foreach (string para in paras)
                        {
                            if (!string.IsNullOrEmpty(para))
                            {
                                string[] para1 = para.Split('=');
                                if (para1.Length == 2)
                                {
                                    routeValues.Add(para1[0], para1[1]);
                                }
                            }
                        }
                    }
                    node.Url = url.Action(item.Action, item.Controller, routeValues);

                    //if (virtualPath != null)
                    //{
                    //    node.Url = "~/" + virtualPath.VirtualPath;
                    //}
                }
            }

            _nodes.Add(item.Code, node);

            return(node);
        }
        //public string Action<TController>(Expression<Action<TController>> action)
        //    where TController : Controller
        //{
        //    var routeValuesFromExpression = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression<TController>(action);
        //    var actionName = routeValuesFromExpression["action"].ToString();
        //    return _mvcUrlHelper.Action(actionName);
        //}

        public string Action(string actionName, string controllerName)
        {
            return(_mvcUrlHelper.Action(actionName, controllerName));
        }
Exemplo n.º 47
0
        private void PrepareScripts()
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>();
            List <string> libraries = new List <string>();

            var request = this.builder.ViewContext.HttpContext.Request;

            if (this.Culture != null)
            {
                parameters.Add("language", this.Culture.TwoLetterISOLanguageName);
            }

            if (this.ApiKey.HasValue())
            {
                parameters.Add("key", this.ApiKey);
            }

            if (this.Layers.Any(l => l.GetType() == typeof(HeatmapLayer)))
            {
                libraries.Add("visualization");
            }

            if (request.IsAjaxRequest())
            {
                parameters.Add("callback", "executeAsync");
            }

            if (!string.IsNullOrWhiteSpace(this.Version))
            {
                parameters.Add("v", this.Version);
            }

            /* Here starts the url composition */

            if (this.Libraries != null)
            {
                libraries.AddRange(this.Libraries);
            }

            string librariesParameterValue = string.Join(",", libraries.Select(l => l.ToLower()).Distinct().ToArray());

            if (!string.IsNullOrEmpty(librariesParameterValue))
            {
                parameters.Add("libraries", librariesParameterValue);
            }

            string queryString = string.Join("&", parameters.Select(dictionaryItem => string.Format("{0}={1}", dictionaryItem.Key, dictionaryItem.Value)));
            var    mainJs      = string.Format(CultureInfo.InvariantCulture, "https://maps.googleapis.com/maps/api/js?{0}", queryString);

            /* Here ends the url composition */

            this.LoadScripts = this.ShouldLoadGoogleScript();
            if (this.LoadScripts)
            {
                this.ScriptFileNames.Add(mainJs);
            }

            if (!request.IsAjaxRequest())
            {
                var urlHelper = new System.Web.Mvc.UrlHelper(this.builder.ViewContext.RequestContext);
                var url       = urlHelper.Action("Scripts", "GMapsMvcApi");
                this.ScriptFileNames.Add(url);
            }
        }