[英]MVC Razor: How to reference helper parameter in Razor markup?
我想將模板參數傳遞給我的幫助器方法以呈現錯誤。 我已經看到了幾個完成此操作的示例,但是它們似乎要求在調用幫助程序時模板中的變量在范圍內。
我希望做這樣的事情:
public static MvcHtmlString ErrorBlock<TModel>(this HtmlHelper helper, TModel model, string @class = null, object context = null, string view = null, object attributes = null, Func<ErrorModel,HelperResult> errorTemplate = null)
where TModel : ErrorModel
...
@ShopMR.ErrorBlock(Model, errorTemplate: r => @<div>@r.Message</div>)
但是我收到以下編譯器錯誤:
我嘗試創建一個委托,但它會導致相同的錯誤。 這可能嗎? 我的func是否應該返回可以編譯/評估為Razor文本的其他某種類型?
要擺脫編譯錯誤,請將rasor更改為:
@ShopMR.ErrorBlock(Model, errorTemplate:r => new HelperResult( x => { x.WriteLine($"<div>r.Message</div>" ); } )
errorTemplate期望返回Lambda表達式,該表達式返回HelperResult模板。
經過一番大驚小怪之后,我想出了一些我喜歡的東西(盡管我確信有一個更干凈的解決方案)
public static MvcHtmlString ErrorBlock<TModel>(this HtmlHelper helper, TModel model,
string @class = null, object context = null, string view = null, object attributes = null,
Func<ErrorModel, Func<ErrorModel,IHtmlString>> errorTemplate = null)
where TModel : BaseModel
{
...
if (errorTemplate != null)
{
var formattedErrors = errors.Select(e => errorTemplate?.Invoke(e)?.Invoke(e)?.ToHtmlString() ?? string.Empty);
tb.InnerHtml = string.Join("", formattedErrors);
}
}
....
這使我可以在調用擴展名時使用預期的語法:
@ShopMR.ErrorBlock(Model, errorTemplate: r => @<div>@r.Message</div>)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.