[英]IE9 unexpected behaviour with MVC, IMG tag, Url.Action and TempData
[英]Is there a way to have @url.Action on an <img> tag
我有一个标签,我正在使用Razor语法。 我使用@ url.Action html帮助器将参数传递给控制器上的方法以检索图片。 但我希望将此图片作为链接,因此当用户单击图片时,它将转到控制器并打开另一个视图。 所以我尝试了以下两种方式,但是它告诉我它缺少“尝试”的“}”。 而对于“Trytwo”它没有给我任何错误,但它没有向我显示图片作为链接。 有任何关于wright方式的想法吗?
tryone
@foreach (var p in Model)
{
<a href= "@Url.Action("Index","Home")>
<img width="50" height="50"
src= "@Url.Action("GetImage", "Sells", new {p.ItemID })" />
</a>
}
trytwo
@foreach (var p in Model)
{
<img href="@Url.Action("Index","Home")" width="50" height="50"
src= "@Url.Action("GetImage", "Sells", new {p.ItemID })" />
}
第一次尝试的问题是href
属性在结束角度括号之前缺少一个右引号。
@foreach (var p in Model)
{
<a href= "@Url.Action("Index","Home")">
<img width="50" height="50"
src= "@Url.Action("GetImage", "Sells", new {p.ItemID })" />
</a>
}
trytwo无法正常工作,因为img
不支持href
属性。
使用正确语法的第一种方法 - 在href
值的末尾添加引号(“)。
我建议您扩展HtmlHelper
。
像这样的东西:
public static class HtmlHelperExtensions
{
public static MvcHtmlString ActionImageLink(this HtmlHelper helper, string controller, string action, object parameters, object linkHtmlAttributes, string src, object imageHtmlAttributes)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = String.IsNullOrWhiteSpace(controller) ? action : urlHelper.Action(action, controller, parameters);
var imgTagBuilder = new TagBuilder("img");
var imgUrl = urlHelper.Content(src);
imgTagBuilder.MergeAttribute("src", imgUrl);
if (imageHtmlAttributes != null)
{
var props = imageHtmlAttributes.GetType().GetProperties();
props.ToList().ForEach(prop => { imgTagBuilder.MergeAttribute(
prop.Name,
imageHtmlAttributes.GetType().GetProperty(prop.Name).GetValue(imageHtmlAttributes, null) as String);
});
}
var image = imgTagBuilder.ToString(TagRenderMode.SelfClosing);
var aTagBuilder = new TagBuilder("a");
aTagBuilder.MergeAttribute("href", url);
if (linkHtmlAttributes != null)
{
var props = linkHtmlAttributes.GetType().GetProperties();
props.ToList().ForEach(prop =>
{
aTagBuilder.MergeAttribute(
prop.Name,
linkHtmlAttributes.GetType().GetProperty(prop.Name).GetValue(linkHtmlAttributes, null) as String);
});
}
aTagBuilder.InnerHtml = image;
return MvcHtmlString.Create(aTagBuilder.ToString());
}}
然后你可以在你的cshtml页面中使用它:
@Html.ActionImageLink("Controller", "action/url", null, null, Url.Content("image/location"), null)
记得创建对扩展类的引用。
参考文献:
扩展HtmlHelpers: http : //www.codeproject.com/Tips/720515/Custom-HTML-Helper-for-MVC-Application
扩展方法: https : //msdn.microsoft.com/en-us/library/bb383977.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.