[英]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.