I have created the following Html Helper Class for displaying a Image:
Class:
namespace MvcWebMobile.CustomHelpers
{
public static class CustomHelper
{
public static string Image(this HtmlHelper helper, string id, string url, string alternateText)
{
return Image(helper, id, url, alternateText, null);
}
public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
{
// Create tag builder
var builder = new TagBuilder("img");
// Create valid id
builder.GenerateId(id);
// Add attributes
builder.MergeAttribute("src", url);
builder.MergeAttribute("alt", alternateText);
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
// Render tag
return builder.ToString(TagRenderMode.SelfClosing);
}
}
}
View:
#Html.Image("img1", "../../Content/images/icons-18-black.png", "logo")
Now when i use the custom helper in my view the Image is not displayed, instead of image following message is printed on web page
<img alt="logo" id="img1" src="../../Content/images/icons-18-black.png" /> <img alt="logo" border="4px" id="img1" src="../../Content/images/icons-18-black.png" />
Your helper should return a HtmlString instead of a string.
public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
return Image(helper, id, url, alternateText, null);
}
public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
{
// ...
return new HtmlString(builder.ToString(TagRenderMode.SelfClosing));
}
Instead of returning string try returning MvcHtmlString,
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
}
Use MvchtmlString:
public static MvcHtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
{
// ...
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}
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 have in my Model:
[Display(Name = "Check to enter <break> the Quantity of items")]
public bool IsLimitedQuantity { get; set; }
and I am using
#Html.LabelFor(shop => shop.IsLimitedQuantity)
in my view.
Please suggest how I can fix this, because the label is just showing <break> as it is, instead of breaking to a new line.
You could write a custom LabelFor helper which doesn't HTML encode the text as does the standard LabelFor helper:
public static class LabelExtensions
{
public static IHtmlString UnencodedLabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
var text = (metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>()));
if (string.IsNullOrEmpty(text))
{
return MvcHtmlString.Empty;
}
var tagBuilder = new TagBuilder("label");
tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tagBuilder.InnerHtml = text;
return new HtmlString(tagBuilder.ToString(TagRenderMode.Normal));
}
}
and then use this custom helper in the view:
#Html.UnencodedLabelFor(x => x.IsLimitedQuantity)
Now the HTML tags in the display name will be rendered without encoding:
[Display(Name = "Check to enter <br/> the Quantity of items")]
public bool IsLimitedQuantity { get; set; }
Using Html decode may help. MVC for security reasons encode all the values.
How to display HTML stored in a database from an ASP.NET MVC view?
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..
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");