我有一个部分视图需要变成通用的。根据这个问题,部分视图无法变成通用的。我写了一个HtmlHelper扩展,处理那些需要类型安全的部分,并将其余部分交给真正的部分视图。通常,在页面加载时调用我的辅助程序,这很好用,但有时我想通过AJAX添加一行或其他内容。当这种情况发生时,控制器无法使用我的“部分视图”,因为它不能访问HtmlHelper。除了使用类型为
object
的模型的部分视图外,有没有其他方法?我正在使用Razor,如果这很重要。这是我正在做的简化版本: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;
}
我意识到在这个例子中,除了局部视图外,我几乎没有代码行,因此似乎没有必要使用helper,但在我的实际例子中,情况更为复杂。
现在,在一个ajax调用中,我想返回Html.DoStuff()
。但是我无法这样做,因为这需要访问HtmlHelper,而在控制器内部无法使用helper。
HtmlHelper
的权限,对吗? - XodarapStringBuilder
实例代替html+=
可以提高性能。 - smartcaveman