您是说您希望某些程序能够在根本不处于控制器上下文中的情况下利用视图,还是您是说您希望能够从控制器内将视图呈现为字符串,而无需调用其他程序控制器?
对于前者,我帮不上什么忙,但对于后者,我们在与所有其他控制器一起继承的基本控制器类型中有这个方法:
/// <summary>
/// Generates a string based on the given PartialViewResult.
/// </summary>
/// <param name="partialViewResult"></param>
/// <returns></returns>
protected internal string RenderPartialViewToString(ViewResultBase partialViewResult)
{
Require.ThatArgument(partialViewResult != null);
var context = ControllerContext;
Require.That(context != null);
using (var sw = new StringWriter())
{
if (string.IsNullOrEmpty(partialViewResult.ViewName))
{
partialViewResult.ViewName = context.RouteData.GetRequiredString("action");
}
ViewEngineResult result;
if (partialViewResult.View == null)
{
result = partialViewResult.ViewEngineCollection.FindPartialView(context, partialViewResult.ViewName);
Require.That(result.View != null,
() => new InvalidOperationException(
"Unable to find view. Searched in: " +
string.Join(",", result.SearchedLocations)));
partialViewResult.View = result.View;
}
var view = partialViewResult.View;
var viewContext = new ViewContext(context, view, partialViewResult.ViewData,
partialViewResult.TempData, sw);
view.Render(viewContext, sw);
return sw.ToString();
}
}
用法:
public ActionResult MyAction(...)
{
var myModel = GetMyModel(...);
string viewString = RenderPartialViewToString(PartialView("MyView", myModel));
// do something with the string
return someAction;
}
我们实际上在基于事件的 AJAX 模型中使用它,其中我们的大多数操作实际上只是返回 AJAX 编码的客户端事件列表,其中一些客户端事件可能是使用字符串更新特定 DOM 元素通过渲染这个局部视图产生。