I'm using MVC3 with Razor.
I have the following helper:
public static class ImageActionLinkHelper
{
public static string ImageActionLink(this AjaxHelper helper, string imageUrl, string actionName, object routeValues, AjaxOptions ajaxOptions)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("alt", "");
var link = helper.ActionLink(builder.ToString(TagRenderMode.SelfClosing), actionName, routeValues, ajaxOptions);
return link.ToHtmlString();
}
}
and in my view I have:
#Ajax.ImageActionLink("../../Content/Images/button_add.png", "JobTasksNew", "TrackMyJob",new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "tmjDynamic" }))
and this is what i get when the page gets rendered
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#tmjDynamic" href="/TrackMyJob/JobTasksNew?Length=10">&lt;img alt=&quot;&quot; src=&quot;../../Content/Images/button_add.png&quot;&gt;&lt;/img&gt;</a>
Microsoft has an example with ajax.actionlink.Replace but I don't have this method.
Can you help me get the correct html string?
Thank you in advance.
Please try this:
public static class ImageActionLinkHelper {
public static MvcHtmlString ImageActionLink(this AjaxHelper helper, string imageUrl, string actionName, object routeValues, AjaxOptions ajaxOptions) {
var builder = new TagBuilder("img");
builder.MergeAttribute("src", imageUrl);
builder.MergeAttribute("alt", "");
var link = helper.ActionLink("[replaceme]", actionName, routeValues, ajaxOptions);
var html = link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
return new MvcHtmlString(html);
}
}
Related
I am trying to understand how I can add an extra parameter to URL.Action, and have it as part of the resultant link.
Lets assume the following:
myParm = "myTestParameterValue";
#Url.Action("Edit", "Order", new { id=item.Id}, null,myParm)
which would result in:
/Order/Edit/1/myTestParameterValue
I would really appreciate some sample code of the extension method for this Action Sample to see how the parameters are taken in and how the link is generated.
I guess it would start something like:
public static MvcHtmlString Action(this HtmlHelper helper, string actionName, string controllerName, object routeValues, boolean IsHashRequired)
If (IsHashRequired)
{
String myHash = GetHash();
}
// Pseudocode .... string myNewLink = ... + myHash
Many thanks in advance
EDIT
I need to calculate hash to add to resultant link. A better parameter would be a boolean. I have edited code accordingly.
EDIT2:
public static IHtmlString Action(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues, string protocol, bool isHashRequired )
{
if (isHashRequired)
{
routeValues["hash"] = "dskjdfhdksjhgkdj"; //Sample value.
}
return urlHelper.Action(???); // Resultant URL = /Order/Edit/1/dskjdfhdksjhgkdj
}
EDIT3:
Struggling with :
return urlHelper.Action(actionName, controllerName, routeValues, protocol);
Apparently needs converting to IHtmlString??
EDIT4:
public static String Action(this UrlHelper urlHelper, string actionName, string controllerName, object routeValues, string protocol, bool isHashRequired )
{
RouteValueDictionary rvd = new RouteValueDictionary(routeValues);
if (isHashRequired)
{
string token = "FDSKGLJDS";
rvd.Add("urltoken", token);
}
return urlHelper.Action(actionName, controllerName, rvd, protocol); //rvd is incorrect I believe
}
EDIT5
return urlHelper.Action(actionName, controllerName, rvd, protocol,null);
where
rvd is the RouteValueDictionary
hostname is null.
Thanks...
You should consider modifying your routes
Where you have your routing configured add something like this:
routes.MapRoute(
"hash", // Route name
"{controller}/{action}/{id}/{hash}", // URL with parameters
new { controller = "Home", action = "Index", id = "", hash = "" } // Parameter defaults
);
And use URL.Action like this:
myParm = "myTestParameterValue";
#Url.Action("Edit", "Order", new { id=item.Id, hash = myParm}, null);
You can easily add this with a new extension method class
public static class MyExtensions
{
public static IHtmlString ActionWithHash(this UrlHelper urlHelper, ....)
{
if (hashRequired)
{
routeParameters["hash"] = ...
}
return urlHelper.Action(...);
}
}
I am trying to add a css class to a #html.actionlink and do not want to use the text that does in the link. I want to use a graphic instead.
Here is my code:
#Html.ActionLink("Edit", "PopupReferenceEdit", new { id = item.VolunteerReferenceID }, new { #class = "Grid-editor" })
When I delete the"Edit" I get an error. Is it possible to use this statement and have an icon/image for the link?
Thanks for answers to this newbie question.
Andy
i think that a more nicer approach for this would be to create an extension method for it with these overloads in your helper folder and then use it in your views. just depends upon the personal preference
public static class ImageActionLinkHelper
{
public static string ImageActionLink(this HtmlHelper helper, string ImageUrl, string altText, string actionName, object routeValues)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", ImageUrl);
builder.MergeAttribute("alt", altText);
builder.MergeAttribute("title", altText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, new { #class = "imgicon" });
return link.ToString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
}
public static string ImageActionLink(this HtmlHelper helper, string ImageUrl, string altText, string actionName, object routeValues, string Id, string display)
{
var builder = new TagBuilder("img");
builder.MergeAttribute("src", ImageUrl);
builder.MergeAttribute("alt", altText);
builder.MergeAttribute("title", altText);
var link = helper.ActionLink("[replaceme]", actionName, routeValues, new { #class = "imgicon", id = Id, style = display });
return link.ToString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing));
}
using it
#Html.ImageActionLink("../../Content/images/edit.png", "Edit", "Edit", new { id = item.UserId})
To get the URL's I wanted i created a simple Link Creator helper for my search results.
But it wont let me use server urlencode in it and some of the details passed are French/Czech/Swedish words commas and apostrophes;
Is there a quick function that will strip all this garbage out before hand?
Create custom HTML helper for this. Generate HTML markup using TagBuilder and use UrlEncode where you want. For example:
public static string SearchActionLink(this HtmlHelper html, string linkText, string actionName, object routeValues)
{
var innerHtml = html.ViewContext.HttpContext.Server.UrlEncode("....");
TagBuilder tagBuilder = new TagBuilder("a") {
InnerHtml = innerHtml;
};
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var url = urlHelper.Action(actionName, routeValues);
tagBuilder.MergeAttribute("href", url);
return tagBuilder.ToString(TagRenderMode.Normal);
}
UPDATED:
Something like this?:
public static string SearchActionLink(this HtmlHelper html, string linkText, System.Web.Routing.RouteValueDictionary routeValues)
{
var ref = html.ViewContext.HttpContext.Server.UrlEncode(routeValues["ref"]);
routeValues["ref"] = "_REF_";
TagBuilder tagBuilder = new TagBuilder("a") { InnerHtml = linkText; };
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var url = urlHelper.RouteUrl(routeValues).Replace("_REF_", ref);
tagBuilder.MergeAttribute("href", url);
return tagBuilder.ToString(TagRenderMode.Normal);
}
The Html.RouteLink() HtmlHelper works great for text links. But what's the best way to link an image?
<img src="..." alt="..." />
Here is mine, it`s the core function make some overloads
public static string ImageLink(this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object routeValues, object htmlAttributes, object imgHtmlAttributes)
{
UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
string imgtag = htmlHelper.Image(imgSrc, alt,imgHtmlAttributes);
string url = urlHelper.Action(actionName, controllerName, routeValues);
TagBuilder imglink = new TagBuilder("a");
imglink.MergeAttribute("href", url);
imglink.InnerHtml =imgtag;
imglink.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
return imglink.ToString();
}
This is an updated version that I have from MiniScalope answer above. I'm using VS2010 and ASP.Net MVC 2 Preview
public static string ImageLink(this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object routeValues, object htmlAttributes, object imgHtmlAttributes)
{
UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
TagBuilder imgTag = new TagBuilder("img");
imgTag.MergeAttribute("src", imgSrc);
imgTag.MergeAttributes((IDictionary<string, string>) imgHtmlAttributes,true);
string url = urlHelper.Action(actionName, controllerName, routeValues);
TagBuilder imglink = new TagBuilder("a");
imglink.MergeAttribute("href", url);
imglink.InnerHtml = imgTag.ToString();
imglink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true);
return imglink.ToString();
}
<%= Html.ActionLink(Html.Image(imageUrl, imageAlt), actionName, controllerName) %>
could work, the image extension is from the futures assembly.
Or make your own extention.
Create your own helper extension.
public static string Image(this HtmlHelper helper, string src, string alt)
{
TagBuilder tb = new TagBuilder("img");
tb.Attributes.Add("src", helper.Encode(src));
tb.Attributes.Add("alt", helper.Encode(alt));
return tb.ToString(TagRenderMode.SelfClosing);
}
I don't have enough SO swagger to add a comment, but this is a comment on
MiniScalope's comment above:
UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
I would suggest making this an HtmlHelper extension method in itself (and simplify it), for reuse:
private static UrlHelper Url(this HtmlHelper helper)
{
return new UrlHelper(helper.ViewContext.RequestContext);
}
<%= Html.RouteLink("PLACEHOLDER", ...).Replace("PLACEHOLDER", "<img src=""..."" alt=""..."" />")%>
this code has been tested on mvc4...
public static MvcHtmlString ImageLink(this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object routeValues, object htmlAttributes, object imgHtmlAttributes)
{
UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
var imgTag = new TagBuilder("img");
imgTag.MergeAttribute("src", imgSrc);
imgTag.MergeAttributes((IDictionary<string, string>)imgHtmlAttributes, true);
string url = urlHelper.Action(actionName, controllerName, routeValues);
var imglink = new TagBuilder("a");
imglink.MergeAttribute("href", url);
imglink.InnerHtml = imgTag.ToString();
imglink.MergeAttributes((IDictionary<string, string>)htmlAttributes, true);
return MvcHtmlString.Create(imglink.ToString());
}
I need to do something like this:
<script type="text/javascript">
token_url = "http://example.com/your_token_url";
</script>
I'm using the Beta version of MVC, but I can't figure out how to get the absolute url of an action. I'd like to do something like this:
<%= Url.AbsoluteAction("Action","Controller")) %>
Is there a helper or Page method for this?
Click here for more information, but esentially there is no need for extension methods. It's already baked in, just not in a very intuitive way.
Url.Action("Action", null, null, Request.Url.Scheme);
Extend the UrlHelper
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static string AbsoluteAction(this UrlHelper url, string action, string controller)
{
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
string absoluteAction = string.Format(
"{0}://{1}{2}",
requestUrl.Scheme,
requestUrl.Authority,
url.Action(action, controller));
return absoluteAction;
}
}
}
Then call it like this
<%= Url.AbsoluteAction("Dashboard", "Account")%>
EDIT - RESHARPER ANNOTATIONS
The most upvoted comment on the accepted answer is This answer is the better one, this way Resharper can still validate that the Action and Controller exists. So here is an example how you could get the same behaviour.
using JetBrains.Annotations
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static string AbsoluteAction(
this UrlHelper url,
[AspMvcAction]
string action,
[AspMvcController]
string controller)
{
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
string absoluteAction = string.Format(
"{0}://{1}{2}",
requestUrl.Scheme,
requestUrl.Authority,
url.Action(action, controller));
return absoluteAction;
}
}
}
Supporting info:
Providing Intellisense, Navigation and more for Custom Helpers in ASP.NET MVC
<%= Url.Action("About", "Home", null, Request.Url.Scheme) %>
<%= Url.RouteUrl("Default", new { Action = "About" }, Request.Url.Scheme) %>
Using
#Charlino 's answer as a guide, I came up with this.
The ASP.NET MVC documentation for UrlHelper shows that Url.Action will return a fully-qualified Url if a hostname and protocol are passed in. I created these helpers to force the hostname and protocol to be provided. The multiple overloads mirror the overloads for Url.Action:
using System.Web.Routing;
namespace System.Web.Mvc {
public static class HtmlExtensions {
public static string AbsoluteAction(this UrlHelper url, string actionName) {
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
return url.Action(actionName, null, (RouteValueDictionary)null,
requestUrl.Scheme, null);
}
public static string AbsoluteAction(this UrlHelper url, string actionName,
object routeValues) {
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
return url.Action(actionName, null, new RouteValueDictionary(routeValues),
requestUrl.Scheme, null);
}
public static string AbsoluteAction(this UrlHelper url, string actionName,
RouteValueDictionary routeValues) {
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
return url.Action(actionName, null, routeValues, requestUrl.Scheme, null);
}
public static string AbsoluteAction(this UrlHelper url, string actionName,
string controllerName) {
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
return url.Action(actionName, controllerName, (RouteValueDictionary)null,
requestUrl.Scheme, null);
}
public static string AbsoluteAction(this UrlHelper url, string actionName,
string controllerName,
object routeValues) {
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
return url.Action(actionName, controllerName,
new RouteValueDictionary(routeValues), requestUrl.Scheme,
null);
}
public static string AbsoluteAction(this UrlHelper url, string actionName,
string controllerName,
RouteValueDictionary routeValues) {
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
return url.Action(actionName, controllerName, routeValues, requestUrl.Scheme,
null);
}
public static string AbsoluteAction(this UrlHelper url, string actionName,
string controllerName, object routeValues,
string protocol) {
Uri requestUrl = url.RequestContext.HttpContext.Request.Url;
return url.Action(actionName, controllerName,
new RouteValueDictionary(routeValues), protocol, null);
}
}
}
Complete answer with arguments would be :
var url = Url.Action("ActionName", "ControllerName", new { id = "arg_value" }, Request.Url.Scheme);
and that will produce an absolute url
I'm not sure if there is a built in way to do it, but you could roll your own HtmlHelper method.
Something like the following
namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static string AbsoluteAction(this HtmlHelper html, string actionUrl)
{
Uri requestUrl = html.ViewContext.HttpContext.Request.Url;
string absoluteAction = string.Format("{0}://{1}{2}",
requestUrl.Scheme,
requestUrl.Authority,
actionUrl);
return absoluteAction;
}
}
}
Then call it like this
<%= Html.AbsoluteAction(Url.Action("Dashboard", "Account"))%> ยป
HTHs,
Charles
Same result but a little cleaner (no string concatenation/formatting):
public static Uri GetBaseUrl(this UrlHelper url)
{
Uri contextUri = new Uri(url.RequestContext.HttpContext.Request.Url, url.RequestContext.HttpContext.Request.RawUrl);
UriBuilder realmUri = new UriBuilder(contextUri) { Path = url.RequestContext.HttpContext.Request.ApplicationPath, Query = null, Fragment = null };
return realmUri.Uri;
}
public static string ActionAbsolute(this UrlHelper url, string actionName, string controllerName)
{
return new Uri(GetBaseUrl(url), url.Action(actionName, controllerName)).AbsoluteUri;
}
Maybe this (?):
<%=
Request.Url.GetLeftPart(UriPartial.Authority) +
Url.Action("Action1", "Controller2", new {param1="bla", param2="blabla" })
%>
env: dotnet core version 1.0.4
Url.Action("Join",null, null,Context.Request.IsHttps?"https":"http");