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'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);
}
}
I want to display images from other sever by using view and controller by asp.net mvc. how can i do? can u tell me detail and give me detail an exmaple? wait to see your answer.
Thanks
Nara
To display image in a view you could use the <img> tag:
<img src="http://someotherserver/path/to/some/image.png" alt="" />
or you could make a little html helper:
public static MvcHtmlString Image(this HtmlHelper helper,
string url,
object htmlAttributes)
{
return Image(helper, url, null, htmlAttributes);
}
public static MvcHtmlString Image(this HtmlHelper helper,
string url,
string altText,
object htmlAttributes)
{
TagBuilder builder = new TagBuilder("image");
var path = url.Split('?');
string pathExtra = "";
if(path.Length >1)
{
pathExtra = "?" + path[1];
}
builder.Attributes.Add("src", VirtualPathUtility.ToAbsolute(path[0]) + pathExtra);
builder.Attributes.Add("alt", altText);
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return MvcHtmlString.Create( builder.ToString(TagRenderMode.SelfClosing));
}
typical usage:
<%=Html.Image("~/content/images/ajax-loader.gif", new{style="margin: 0 auto;"})%>
enjoy..
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);
}
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");