本文整理汇总了C#中System.Web.Mvc.UrlHelper类的典型用法代码示例。如果您正苦于以下问题:C# UrlHelper类的具体用法?C# UrlHelper怎么用?C# UrlHelper使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
UrlHelper类属于System.Web.Mvc命名空间,在下文中一共展示了UrlHelper类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: Applies
public bool Applies(ShoppingCartQuantityProduct quantityProduct, IEnumerable<ShoppingCartQuantityProduct> cartProducts) {
if (DiscountPart == null) return false;
var now = _clock.UtcNow;
if (DiscountPart.StartDate != null && DiscountPart.StartDate > now) return false;
if (DiscountPart.EndDate != null && DiscountPart.EndDate < now) return false;
if (DiscountPart.StartQuantity != null &&
DiscountPart.StartQuantity > quantityProduct.Quantity)
return false;
if (DiscountPart.EndQuantity != null &&
DiscountPart.EndQuantity < quantityProduct.Quantity)
return false;
if (!string.IsNullOrWhiteSpace(DiscountPart.Pattern)) {
string path;
if (DiscountPart.DisplayUrlResolver != null) {
path = DiscountPart.DisplayUrlResolver(quantityProduct.Product);
}
else {
var urlHelper = new UrlHelper(_wca.GetContext().HttpContext.Request.RequestContext);
path = urlHelper.ItemDisplayUrl(quantityProduct.Product);
}
if (!path.StartsWith(DiscountPart.Pattern, StringComparison.OrdinalIgnoreCase))
return false;
}
if (DiscountPart.Roles.Any()) {
var user = _wca.GetContext().CurrentUser;
if (user.Has<UserRolesPart>()) {
var roles = user.As<UserRolesPart>().Roles;
if (!roles.Any(r => DiscountPart.Roles.Contains(r))) return false;
}
}
return true;
}
开发者ID:richinoz,项目名称:Orchard1.6,代码行数:32,代码来源:Discount.cs
示例2: ImageActionLink
public static MvcHtmlString ImageActionLink(
this HtmlHelper helper,
string imageUrl,
string altText,
string actionName,
string controllerName,
object routeValues,
object linkHtmlAttributes,
object imgHtmlAttributes)
{
var linkAttributes = AnonymousObjectToKeyValue(linkHtmlAttributes);
var imgAttributes = AnonymousObjectToKeyValue(imgHtmlAttributes);
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", imageUrl);
imgBuilder.MergeAttribute("alt", altText);
imgBuilder.MergeAttributes(imgAttributes, true);
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
var linkBuilder = new TagBuilder("a");
linkBuilder.MergeAttribute("href", urlHelper.Action(actionName, controllerName, routeValues));
linkBuilder.MergeAttributes(linkAttributes, true);
var text = linkBuilder.ToString(TagRenderMode.StartTag);
text += imgBuilder.ToString(TagRenderMode.SelfClosing);
text += linkBuilder.ToString(TagRenderMode.EndTag);
return MvcHtmlString.Create(text);
}
开发者ID:KirillMehtiev,项目名称:Collective,代码行数:25,代码来源:ImageActionLinkExtention.cs
示例3: Application_PostAuthenticateRequest
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
try
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (authTicket.UserData == "OAuth") return;
var currentUser = serializer.Deserialize<CurrentUserPrincipal>(authTicket.UserData);
currentUser.SetIdentity(authTicket.Name);
HttpContext.Current.User = currentUser;
}
}
catch (Exception ex)
{
ErrorSignal.FromCurrentContext().Raise(ex);
FormsAuthentication.SignOut();
HttpCookie oldCookie = new HttpCookie(".ASPXAUTH");
oldCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(oldCookie);
HttpCookie ASPNET_SessionId = new HttpCookie("ASP.NET_SessionId");
ASPNET_SessionId.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(ASPNET_SessionId);
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
Response.Redirect(urlHelper.Action(MVC.OAuth.ActionNames.SignIn, MVC.OAuth.Name));
}
}
开发者ID:YekanPedia,项目名称:ManagementSystem,代码行数:32,代码来源:Global.asax.cs
示例4: GetNotifications
public IEnumerable<NotifyEntry> GetNotifications() {
if ( string.IsNullOrWhiteSpace(_orchardServices.WorkContext.CurrentSite.BaseUrl)) {
var urlHelper = new UrlHelper(_workContext.HttpContext.Request.RequestContext);
var url = urlHelper.Action("Index", "Admin", new {Area = "Settings"});
yield return new NotifyEntry { Message = T("The Warmup feature needs the <a href=\"{0}\">Base Url site setting</a> to be set.", url), Type = NotifyType.Warning };
}
}
开发者ID:SunRobin2015,项目名称:RobinWithOrchard,代码行数:7,代码来源:SettingsBanner.cs
示例5: EntryToEntryViewModelMapper
public EntryToEntryViewModelMapper(
IDocumentSession session,
UrlHelper urlHelper)
{
this.session = session;
this.urlHelper = urlHelper;
}
开发者ID:bbqchickenrobot,项目名称:byteblog,代码行数:7,代码来源:EntryToEntryViewModelMapper.cs
示例6: SetLinks
protected void SetLinks(AtomEntry e)
{
LogService.Debug("AnnotateService.SetLinks entryId={0}", e.Id);
var links = e.Links.ToList();
var url = new UrlHelper(Container.GetInstance<RequestContext>());
//atom threading extension
if (e.InReplyTo != null)
{
e.InReplyTo.Href = url.RouteIdUri("AtomPubResource", e.InReplyTo.Ref, AbsoluteMode.Force);
links.Merge(new AtomLink
{
Rel = "related",
Type = "text/html",
Href = url.RouteIdUri("AtomPubResource", e.InReplyTo.Ref, AbsoluteMode.Force)
});
}
//atom threading extension
links.Merge(new AtomLink
{
Href = url.RouteIdUri("AnnotateEntryAnnotationsFeed", e.Id, AbsoluteMode.Force),
Rel = "replies",
Type = Atom.ContentType,
Count = e.Total,
Updated = DateTimeOffset.UtcNow
});
e.Links = links;
}
开发者ID:erikzaadi,项目名称:atomsitethemes.erikzaadi.com,代码行数:28,代码来源:AnnotateService.cs
示例7: HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAjaxRequest())
{
var urlHelper = new UrlHelper(context.RequestContext);
context.HttpContext.Response.StatusCode = 403;
context.Result = new JsonResult
{
Data = new
{
Error = "NoPermission",
LogOnUrl = urlHelper.Action("index", "login")
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
context.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "index" },
{ "controller", "error" },
{ "id", (int)ErrorType.NoPermission},
{"returnurl",context.RequestContext.HttpContext.Request.Url}
});
}
}
开发者ID:navy235,项目名称:PadCrm,代码行数:31,代码来源:PermissionAuthorizeAttribute.cs
示例8: Generate
public static string Generate(RequestContext requestContext, NavigationRequest navigationItem, RouteValueDictionary routeValues)
{
if (requestContext == null)
throw new ArgumentNullException("requestContext");
if (navigationItem == null)
throw new ArgumentNullException("navigationItem");
var urlHelper = new UrlHelper(requestContext);
string generatedUrl = null;
if (!string.IsNullOrEmpty(navigationItem.RouteName))
{
generatedUrl = urlHelper.RouteUrl(navigationItem.RouteName, routeValues);
}
else if (!string.IsNullOrEmpty(navigationItem.ControllerName) && !string.IsNullOrEmpty(navigationItem.ActionName))
{
generatedUrl = urlHelper.Action(navigationItem.ActionName, navigationItem.ControllerName, routeValues, null, null);
}
else if (!string.IsNullOrEmpty(navigationItem.Url))
{
generatedUrl = navigationItem.Url.StartsWith("~/", StringComparison.Ordinal)
? urlHelper.Content(navigationItem.Url)
: navigationItem.Url;
}
else if (routeValues.Any())
{
generatedUrl = urlHelper.RouteUrl(routeValues);
}
return generatedUrl;
}
开发者ID:modulexcite,项目名称:FluentHtml,代码行数:32,代码来源:UrlGenerator.cs
示例9: GenerateContentUrl
public string GenerateContentUrl(string relativePath)
{
var httpRequest = GetCurrentRequest();
var urlHelper = new UrlHelper(httpRequest.RequestContext, RouteTable.Routes);
return urlHelper.Content(relativePath);
}
开发者ID:zeshan-iqbal,项目名称:DustedCodes,代码行数:7,代码来源:UrlGenerator.cs
示例10: RenderApplicationUrls
public static IHtmlString RenderApplicationUrls(this HtmlHelper helper)
{
var url = new UrlHelper(helper.ViewContext.RequestContext);
var applicationUrls = new
{
LoginUrl = url.Action(MVC.Authentication.Login()),
LogoutUrl = url.Action(MVC.Authentication.Logout()),
LoginCheckUrl = url.Action(MVC.Authentication.LoginCheck()),
ListUsersUrl = url.Action("Index", "Api/Users"),
CreateUserUrl = url.Action("Create", "Api/Users"),
UpdateUserUrl = url.Action("Update", "Api/Users"),
DeleteUsersUrl = url.Action("Delete", "Api/Users"),
ListDashboardPermissionsUrl = url.Action("Index", "Api/DashboardPermissions"),
ListMessagesUrl = url.Action("Index", "Api/Messages"),
CreateMessageUrl = url.Action("Create", "Api/Messages"),
DeleteMessagesUrl = url.Action("Delete", "Api/Messages"),
ListOrganizationsUrl = url.Action("Index", "Api/Organizations"),
CreateOrganizationUrl = url.Action("Create", "Api/Organizations"),
UpdateOrganizationUrl = url.Action("Update", "Api/Organizations"),
DeleteOrganizationsUrl = url.Action("Delete", "Api/Organizations"),
ListRolesUrl = url.Action("Index", "Api/Roles")
};
var script = @"<script type='text/javascript'>
angular.module('colorSoft').constant('ApplicationUrls', <INSERT_URLS>);
</script>".Replace("<INSERT_URLS>", CreateJavascriptHash(applicationUrls));
return MvcHtmlString.Create(script);
}
开发者ID:mattapayne,项目名称:ColorSoft,代码行数:30,代码来源:HtmlHelperExtensions.cs
示例11: PackageListViewModel
public PackageListViewModel(
IQueryable<Package> packages,
DateTime? indexTimestampUtc,
string searchTerm,
int totalCount,
int pageIndex,
int pageSize,
UrlHelper url,
string curatedFeed)
{
// TODO: Implement actual sorting
IEnumerable<ListPackageItemViewModel> items = packages.ToList().Select(pv => new ListPackageItemViewModel(pv));
PageIndex = pageIndex;
IndexTimestampUtc = indexTimestampUtc;
PageSize = pageSize;
TotalCount = totalCount;
SearchTerm = searchTerm;
int pageCount = (TotalCount + PageSize - 1) / PageSize;
var pager = new PreviousNextPagerViewModel<ListPackageItemViewModel>(
items,
PageIndex,
pageCount,
page => curatedFeed == null ?
url.PackageList(page, searchTerm) :
url.CuratedPackageList(page, searchTerm, curatedFeed)
);
Items = pager.Items;
FirstResultIndex = 1 + (PageIndex * PageSize);
LastResultIndex = FirstResultIndex + Items.Count() - 1;
Pager = pager;
}
开发者ID:hugoparedes,项目名称:NuGetGallery,代码行数:32,代码来源:PackageListViewModel.cs
示例12: ActionImage
/// <summary>
/// Creates and Action link with a clickable image instead of text.
/// </summary>
/// <param name="helper"></param>
/// <param name="controller">Controller</param>
/// <param name="action">Action</param>
/// <param name="parameters">Parameters</param>
/// <param name="src">Image source</param>
/// <param name="alt">Alternate text(Optional)</param>
/// <returns>An HTML anchor tag with a nested image tag.</returns>
public static MvcHtmlString ActionImage(this HtmlHelper helper, String controller, String action, Object parameters, String src, String alt = "", String title = "")
{
var tagBuilder = new TagBuilder("img");
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = urlHelper.Action(action, controller, parameters);
var imgUrl = urlHelper.Content(src);
var image = "";
var html = new StringBuilder();
// build the image tag.
tagBuilder.MergeAttribute("src", imgUrl);
tagBuilder.MergeAttribute("alt", alt);
tagBuilder.MergeAttribute("width", "100");
tagBuilder.MergeAttribute("height", "100");
tagBuilder.MergeAttribute("title", title);
image = tagBuilder.ToString(TagRenderMode.SelfClosing);
html.Append("<a href=\"");
html.Append(url);
html.Append("\">");
html.Append(image);
html.Append("</a>");
return MvcHtmlString.Create(html.ToString());
}
开发者ID:haithemaraissia,项目名称:Test,代码行数:35,代码来源:ImageHelper.cs
示例13: BuildMainMenuItems
/// <summary>
/// Builds main menu
/// </summary>
public static MvcHtmlString BuildMainMenuItems(this HtmlHelper helper, UrlHelper urlHelper, string activeItemTitle)
{
var sb = new StringBuilder();
var menuItems = new[]{
new MenuItem("Главная", urlHelper.RouteUrl("Main")),
new MenuItem("Программы",urlHelper.RouteUrl("AllTravels")),
new MenuItem("Расписание", urlHelper.RouteUrl("EventSchedule")),
new MenuItem("Статьи", urlHelper.RouteUrl("AllArticles")),
new MenuItem("Фотогалерея", urlHelper.RouteUrl("AllAlbums")),
new MenuItem("Книги", urlHelper.RouteUrl("AllBooks")),
new MenuItem("Новости", urlHelper.RouteUrl("AllNews")),
new MenuItem("Отзывы", "javascript:notImplemented()"),
new MenuItem("Цены", "javascript:notImplemented()"),
new MenuItem("Контакты", "javascript:notImplemented()")
};
foreach (var menuItem in menuItems)
{
sb.AppendLine(
string.Format("<li {0}><a href='{1}'>{2}</a></li>",
(menuItem.Title == activeItemTitle) ? "class='active'" : string.Empty,
menuItem.Url,
menuItem.Title));
}
return new MvcHtmlString(sb.ToString());
}
开发者ID:kidaa,项目名称:Indigo,代码行数:28,代码来源:Helpers.cs
示例14: OnActionExecuted
/// <summary>
/// Called by the ASP.NET MVC framework after the action method executes.
/// </summary>
/// <param name="filterContext">The filter context.</param>
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext == null || !filterContext.HttpContext.Request.IsAjaxRequest())
{
return;
}
// Preparing Json object for AJAX.success processing in forms.js javascript
string destinationUrl = string.Empty;
if (filterContext.Result is RedirectResult)
{
var result = filterContext.Result as RedirectResult;
destinationUrl = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext);
}
if (filterContext.Result is RedirectToRouteResult)
{
var result = filterContext.Result as RedirectToRouteResult;
var helper = new UrlHelper(filterContext.RequestContext);
destinationUrl = helper.RouteUrl(result.RouteValues);
}
// Rendered context is getting reloaded by AJAX.success in forms.js javascript
if (filterContext.Result is ViewResult)
{
return;
}
var jsonResult = new JsonResult { Data = new { resultType = "Redirect", redirectUrl = destinationUrl } };
filterContext.Result = jsonResult;
}
开发者ID:targitaj,项目名称:m3utonetpaleyerxml,代码行数:35,代码来源:FormValidatorAttribute.cs
示例15: Rsd
public ActionResult Rsd(string blogPath) {
Logger.Debug("RSD requested");
BlogPart blogPart = _blogService.Get(blogPath);
if (blogPart == null)
return HttpNotFound();
const string manifestUri = "http://archipelago.phrasewise.com/rsd";
var urlHelper = new UrlHelper(ControllerContext.RequestContext, _routeCollection);
var url = urlHelper.Action("", "", new { Area = "XmlRpc" });
var options = new XElement(
XName.Get("service", manifestUri),
new XElement(XName.Get("engineName", manifestUri), "Orchard CMS"),
new XElement(XName.Get("engineLink", manifestUri), "http://orchardproject.net"),
new XElement(XName.Get("homePageLink", manifestUri), "http://orchardproject.net"),
new XElement(XName.Get("apis", manifestUri),
new XElement(XName.Get("api", manifestUri),
new XAttribute("name", "MetaWeblog"),
new XAttribute("preferred", true),
new XAttribute("apiLink", url),
new XAttribute("blogID", blogPart.Id))));
var doc = new XDocument(new XElement(
XName.Get("rsd", manifestUri),
new XAttribute("version", "1.0"),
options));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
return Content(doc.ToString(), "text/xml");
}
开发者ID:rupertwhitlock,项目名称:IncreasinglyAbsorbing,代码行数:33,代码来源:RemoteBlogPublishingController.cs
示例16: LoadMenuItems
/// <summary>
/// Loads the menu items.
/// </summary>
/// <param name="urlHelper">The URL helper.</param>
/// <param name="runAsTenant">The run as tenant id.</param>
/// <returns></returns>
public static IList<MenuItem> LoadMenuItems(UrlHelper urlHelper)
{
var repo = ServiceLocator.Current.GetInstance<IRepositoryFactory>();
var repoMenu = repo.CreateWithGuid<Menu>();
var menus = repoMenu.GetAll().ToList();
var items = new List<MenuItem>();
foreach (var menu in menus)
{
var link = string.Empty;
link = urlHelper.RouteUrl("Default", new { controller = menu.Controller, action = menu.Action });
var item = new MenuItem()
{
Text = menu.Name,
Link = link,
IsAdministration = menu.IsAdministration
};
items.Add(item);
}
//var items = new List<MenuItem>();
if (items == null)
items = new List<MenuItem>();
return items;
}
开发者ID:khoacoi,项目名称:ChatHubRD,代码行数:35,代码来源:MenuHelper.cs
示例17: PackageListViewModel
public PackageListViewModel(IQueryable<Package> packages,
string searchTerm,
string sortOrder,
int totalCount,
int pageIndex,
int pageSize,
UrlHelper url,
bool includePrerelease)
{
// TODO: Implement actual sorting
IEnumerable<ListPackageItemViewModel> items;
using (MiniProfiler.Current.Step("Querying and mapping packages to list"))
{
items = packages.ToList()
.Select(pv => new ListPackageItemViewModel(pv, needAuthors: false));
}
PageIndex = pageIndex;
PageSize = pageSize;
TotalCount = totalCount;
SortOrder = sortOrder;
SearchTerm = searchTerm;
int pageCount = (TotalCount + PageSize - 1) / PageSize;
var pager = new PreviousNextPagerViewModel<ListPackageItemViewModel>(
items,
PageIndex,
pageCount,
page => url.PackageList(page, sortOrder, searchTerm, includePrerelease)
);
Items = pager.Items;
FirstResultIndex = 1 + (PageIndex * PageSize);
LastResultIndex = FirstResultIndex + Items.Count() - 1;
Pager = pager;
IncludePrerelease = includePrerelease ? "true" : null;
}
开发者ID:Redsandro,项目名称:chocolatey.org,代码行数:35,代码来源:PackageListViewModel.cs
示例18: GetActionAbsoluteUrl
public static string GetActionAbsoluteUrl(UrlHelper urlHelper, string actionName, string controllerName, object routeValues)
{
var baseUri = new Uri(GetWebRootUrl());
string relativeUri = urlHelper.Action(actionName, controllerName, routeValues);
var uri = new Uri(baseUri, relativeUri);
return uri.AbsoluteUri;
}
开发者ID:MulderFox,项目名称:Main,代码行数:7,代码来源:Url.cs
示例19: Process
public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model)
{
if (model.Exception != null)
throw model.Exception;
var client = model.AuthenticatedClient;
var username = client.UserInformation.UserName;
FormsAuthentication.SetAuthCookie(username, false);
context.Response.AppendCookie(new HttpCookie("AccessToken", client.AccessToken.SecretToken)
{
Secure = !context.IsDebuggingEnabled,
HttpOnly = true
});
var urlHelper = new UrlHelper(((MvcHandler)context.Handler).RequestContext);
var redirectUrl = string.Format("/{0}/", username);
var cookie = context.Request.Cookies["returnUrl"];
if (cookie != null && urlHelper.IsLocalUrl(cookie.Value))
{
redirectUrl = cookie.Value;
cookie.Expires = DateTime.Now.AddDays(-1);
context.Response.Cookies.Add(cookie);
}
return new RedirectResult(redirectUrl);
}
开发者ID:nikmd23,项目名称:signatory,代码行数:28,代码来源:AuthenticationCallbackController.cs
示例20: ServerVariablesParser_Parsing
void ServerVariablesParser_Parsing(object sender, Dictionary<string, object> e)
{
if (HttpContext.Current == null) return;
var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
var mainDictionary = new Dictionary<string, object>
{
{
"ocBaseUrl",
urlHelper.GetUmbracoApiServiceBaseUrl<ObjectController>(controller => controller.PostCreate(null))
},
{
"pecBaseUrl",
urlHelper.GetUmbracoApiServiceBaseUrl<PropertyEditorsApiController>(
controller => controller.GetAllTypes())
},
{
"fcBaseUrl",
urlHelper.GetUmbracoApiServiceBaseUrl<FieldApiController>(controller => controller.GetAllUsers())
}
};
if (!e.Keys.Contains("uioMatic"))
{
e.Add("uioMatic", mainDictionary);
}
}
开发者ID:TimGeyssens,项目名称:UIOMatic,代码行数:27,代码来源:ServerVariableParserEvent.cs
注:本文中的System.Web.Mvc.UrlHelper类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论