我有一個局部視圖,我想通用。根據this question,部分視圖不能是通用的。所以我反而做了一個HtmlHelper擴展,它處理我想要的類型安全的部分,然後將其餘的部分交給真正的局部視圖。ASP.NET MVC通用局部視圖模式
通常我的助手是在頁面加載時調用的,它工作正常,但有時我想通過AJAX添加一行或其他東西。發生這種情況時,控制器無法使用我的「局部視圖」,因爲它無法訪問HtmlHelper。
除了用object
類型的模型進行局部視圖外,有什麼我可以做的嗎?
我使用剃刀,如果這很重要。
的我在做什麼的簡化版本:
public static MvcHtmlString DoStuff<T>(this HtmlHelper html, IEnumerable<T> data,
Func<T, ViewModelType> StronglyTypedFn, string PartialName)
{
// the pre- and post-processing for the partial view is complex enough I'd like
// to encapsulate it. But I want the encapsulation to include the safety
// benefits that generics give.
var mappedData = data.Select(StronglyTypedFn);
string htmlData = "";
foreach(var model in mappedData){
htmlData += html.Partial(PartialName, model);
}
htmlData += "some boilerplate footer html";
return htmlData;
}
我意識到,在這個例子中,我有,它似乎毫無意義的具有助手的局部視圖之外的代碼,這樣幾行,但在我真實的例子是比較複雜的。
現在,在ajax調用中,我想返回Html.DoStuff()
。但我不能,因爲這需要訪問HtmlHelper,並且幫助程序在控制器內不可用。
我不完全瞭解您的情況。你能否展示這位助手是怎樣的以及你如何從你的視線中調用它? – 2011-02-16 18:15:05
@Darin:我添加了一個例子。可能有更好的方法來完成這與我如何完成它無關。 – Xodarap 2011-02-16 18:25:43