我有一个标签,我使用Razor语法。我使用@url.Action html助手向控制器上的方法传递一个参数以检索图片。但是我希望将这张图片作为链接,所以当用户单击图片时,它会转到控制器并打开一个不同的视图。因此,我尝试了下面的两种方式显示,但它告诉我,它缺少一个"}“的"Tryone”。对于"Trytwo“,它没有给我任何错误,但它并没有显示给我的图片作为一个链接。对赖特的方法有什么想法吗?
崔恩
@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>
}试二
@foreach (var p in Model)
{
<img href="@Url.Action("Index","Home")" width="50" height="50"
src= "@Url.Action("GetImage", "Sells", new {p.ItemID })" />
}发布于 2015-06-01 20:49:13
第一次尝试的一个问题是,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>
}发布于 2015-06-01 20:53:29
因为img不支持href属性,第二次尝试不起作用。
用正确的语法使用第一种方法--在href值的末尾添加引号(")。
发布于 2015-06-01 20:58:11
我建议您扩展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://stackoverflow.com/questions/30582968
复制相似问题