我有一个部分的观点,我想成为通用的。根据this question ,部分 View 不能是通用的。所以我做了一个 HtmlHelper 扩展来处理我想要类型安全的部分,然后将其余部分交给真正的部分 View 。
通常我的助手在页面加载时被调用,这工作正常,但有时我想通过 AJAX 添加一行或其他内容。发生这种情况时, Controller 无法使用我的“部分 View ”,因为它无法访问 HtmlHelper。
除了具有类型为 object
的模型的局部 View 之外,有什么我可以做的吗?
如果这很重要,我正在使用 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;
}
我意识到在这个例子中,我在局部 View 之外的代码行太少了,有一个助手似乎毫无意义,但在我的真实例子中,它更复杂。
现在,在 ajax 调用中,我想返回
Html.DoStuff()
.但我不能,因为这需要访问 HtmlHelper,而该助手在 Controller 中不可用。
最佳答案
你可以有一个简单的 Action 方法来调用一个模型实例的部分
public PartialViewResult Single(string partialName) {
return PartialView(partialName);
}
关于asp.net-mvc - ASP.NET MVC 通用局部 View 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5020377/