有没有办法向Action和Model组合发出GET请求以返回HTML,而不是向URI发出GET请求?
通常在我的代码中我会做
return View("myView", myModel);
我想从中返回HTML,并且能够阅读HTML。
类似的东西:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
但要传递动作和模型
答案 0 :(得分:0)
有一些available here,您可以将模型作为参数传递。虽然仍然不确定为什么要这样做......替代来源available on github。
无论如何,如果您只是想以某种方式改变HTML,另一种方法是重定向到视图,然后使用动作过滤器,您可以在其中进行任何可能需要的后处理。
这样做会将任何视图渲染为HTML并将其作为String
返回。
虽然是较大类的一部分,但相关部分位于下方(Context
实际为Controller.ControllerContext
):
/// <summary>
/// Internal method that handles rendering of either partial or
/// or full views.
/// </summary>
/// <param name="viewPath">
/// The path to the view to render. Either in same controller, shared by
/// name or as fully qualified ~/ path including extension
/// </param>
/// <param name="model">Model to render the view with</param>
/// <param name="partial">Determines whether to render a full or partial view</param>
/// <returns>String of the rendered view</returns>
protected string RenderViewToStringInternal(string viewPath, object model,
bool partial = false)
{
// first find the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, null);
if (viewEngineResult == null)
throw new FileNotFoundException(Resources.ViewCouldNotBeFound);
// get the view and attach the model to view data
var view = viewEngineResult.View;
Context.Controller.ViewData.Model = model;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(Context, view,
Context.Controller.ViewData,
Context.Controller.TempData,
sw);
view.Render(ctx, sw);
result = sw.ToString();
}
return result;
}