1 回答

TA貢獻1794條經驗 獲得超8個贊
在視圖中,您可以使用 從路由值、操作和控制器生成 URL,并在屬性中使用該 URL。若要在 HTML 幫助程序中執行此操作,需要構造自己的 URL 幫助程序。Url.Action()href
// ASP.NET MVC
UrlHelper urlHelper = new UrlHelper(
helper.ViewContext.RequestContext,
helper.RouteCollection);
// ASP.NET Core
UrlHelper urlHelper = new UrlHelper(
new ActionContext(
helper.ViewContext.HttpContext,
helper.ViewContext.RouteData,
helper.ViewContext.ActionDescriptor));
現在,這部分代碼:
string routeValuesToString = "?";
foreach(var r in new RouteValueDictionary(routeValues))
{
routeValuesToString += r.Key.ToString()+"="+r.Value.ToString()+"&";
}
routeValuesToString.Remove(routeValuesToString.Length-1);
anchorStart.MergeAttribute("href", "../"+controllerName+"/"+actionName+"/"
+ routeValuesToString);
可以簡化為:
anchorStart.MergeAttribute("href",
urlHelper.Action(actionName, controllerName, routeValues));
當路徑是路由的一部分時,這會正確地將值放在路徑中,并將其余值放在查詢字符串中。
編輯 - 我提到了標簽助手以及它們的可組合性。您的HTML幫助程序正在做很多與圖標本身無關的事情,只是為了使其成為一個鏈接。HTML 幫助程序可以采用呈現委托,但您仍在使用自己的 HTML 幫助程序作為標記。a
這是一個簡單的標簽幫助程序,它將為您提供一個FontAwesome圖標。icon
[HtmlTargetElement("icon", Attributes = "")]
public class IconTagHelper : TagHelper
{
[HtmlAttributeName("name")]
public string IconName { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "span";
string classAttribute = $@"fa fa-{IconName}";
output.Attributes.Add("class", classAttribute);
}
}
現在,您可以將普通標記與 asp-* 標記幫助程序屬性結合使用,并向標記添加任何其他屬性(如 data-id)。aicon
<a asp-action="someAction" asp-controller="theController" asp-route-id="@Model.Id"><icon name="fa-thumbs-up" data-id="@Model.Id" /></a>
使用 ,它將呈現如下內容:Model.Id == 1
<a href="/theController/someAction/1"><span class="fa fa-thumbs-up" data-id="1"></span></a>
換句話說,標記幫助程序唯一關心的是如何將原始參數轉換為表示圖標的標記。其他所有內容(錨點標簽構造、其他屬性等)都可以留給更適合這些任務的其他內容。這是一個美麗的關注點分離。iconName
為此,您可能需要重構方法,甚至將該代碼引入標記幫助程序,具體取決于它的作用。MaterialIcon
- 1 回答
- 0 關注
- 81 瀏覽
添加回答
舉報