gpt4 book ai didi

asp.net-mvc - 自定义助手无法正常工作

转载 作者:行者123 更新时间:2023-12-04 02:45:01 28 4
gpt4 key购买 nike

我创建了以下用于显示图像的 Html Helper 类:

类:

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);
}
}
}

查看:

@Html.Image("img1", "../../Content/images/icons-18-black.png", "logo")

现在,当我在我的 View 中使用自定义助手时,不显示图像,而是在网页上打印以下消息,而不是图像

<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" /> 

最佳答案

您的助手应该返回一个 HtmlString 而不是 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));
}

关于asp.net-mvc - 自定义助手无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003298/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com