簡體   English   中英

使用對象名稱作為與ActionLink的鏈接,而不是硬編碼字面量

[英]Use Object Name as Link with ActionLink, Not Hard-coded Literal

我試圖讓我的WebGrid使用我的實體的名稱作為鏈接。 如果我只是這樣做:

grid.Column("Name"),

網格在網格的每一行中顯示實體的名稱:

在此處輸入圖片說明

但是,我希望該名稱顯示為鏈接。 我最接近完成這項工作的方法是:

grid.Column("Name", format: (item) => @Html.ActionLink("Edit", "Edit", new { id = item.Id })),

在此處輸入圖片說明

但是,正如您所看到的,每個名稱都是Edit。 如何在那里找到實際的對象名稱? 我嘗試了此操作,但遇到一個錯誤(唯一的區別是,我嘗試使用item.Name代替“ Edit”作為ActionLink方法的第一個參數):

grid.Column("Name", format: (item) => @Html.ActionLink(item.Name, "Edit", new { id = item.Id })),

錯誤: TrackerJob>>' has no applicable method named 'ActionLink' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. TrackerJob>>' has no applicable method named 'ActionLink' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

格式是func,其輸入參數的類型為dynamic,並且作為item的結果類型。名稱在編譯時也是動態的。 如錯誤所述,請使用以下代碼:

grid.Column("Name", format: (item) => @Html.ActionLink((string)item.Name, "Edit", new { id = item.Id })

嘗試交換參數?

grid.Column("Name", format: (item) => @Html.ActionLink("Edit", item.Name, new { id = item.Id }))

在第一個評論之后

嘗試使用帶有更多參數的ActionLink重載( 從此處開始 ):

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    RouteValueDictionary routeValues,
    IDictionary<string, Object> htmlAttributes
)

由於僅字符串會導致重載變得模棱兩可。 在定義ActionLink時,也可以使用命名參數。

試圖尋找GetSelectLink()嗎? 此處的更多信息: http : //weblogs.asp.net/andrebaltieri/archive/2010/11/02/asp-net-mvc-3-working-with-webgrid-part-2.aspx

就個人而言,我會堅持自己制作桌子-當它們變得更個性化時,我會覺得它不太混亂,但這是我的觀點。

編輯:您可以做這樣的事情,但是我再次強調,您有點擺脫了“簡單”的觀點:

item.GetSelectLink(String.Format("<a href='{0}'>{1}</a>", Url.Action("Edit", new { id = item.Id }), item.Name))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM